我想用这些条件合并2个列表
List<int> A = {1,1,1,null,null,null,null,null,null};
List<int> B = {null,null,null,2,2,2,null,null,null};
合并
后的结果List<int> C = {1,1,1,2,2,2,null,null,null}
其中list A
中的null
值将替换为list B
中的值,另外,如果有1 , null, 1, null
这样的情况,我尝试使用它的for循环,但我花费了很多性能,我想要一个合适的方法来做
for(int i = 0; i <A.size; i++)
{
for(int j=0 ;j <B.size; j++)
}
从我对这个问题的理解
案例1:如果两个list的大小相等,那么你可以使用Java流API编写一个没有任何循环的一致代码。
List<Integer> C = IntStream.range(0, A.size())
.mapToObj(i -> {
Integer a = A.get(i);
Integer b = A.get(i);
if (a == null && b != null) {
return b;
} else if (a != null && b == null) {
return a;
} else {
// assuming when both the value are present
// you want to return from list A
return a;
}
})
.collect(Collectors.toList());
案例2:如果两个列表的大小不等。
List<Integer> C = IntStream.range(0, Math.max(A.size(), B.size()))
.mapToObj(i -> {
Integer a = i < A.size() ? A.get(i) : null;
Integer b = i < B.size() ? B.get(i) : null;
if (a == null && b != null) {
return b;
} else if (a != null && b == null) {
return a;
} else {
// assuming when both the value are present
// you want to return from list A
return a;
}
})
.collect(Collectors.toList());
2个循环意味着你的代码运行内部位A * B
次,这是你不想要的。如果A和B的大小相等,您只需要运行'A'次,如果不相等,则运行max(A.size(), B.size())
次。
var out = new ArrayList<Integer>();
for (int i = 0; i < a.size(); i++) {
Integer v = a.get(0);
if (v == null) v = b.get(0);
out.add(v);
}