I want merging 2 list with these conditions
List<int> A = 1,1,1,nul,null,null,null,null,null
List<int> B = null,null,null,2,2,2,null,null,null
The result i want after merging
List<int> C = 1,1,1,2,2,2,null,null,null
where null value in list A will replace with value in list B, Also in case there will have a case like: 1 , null , 1, null, i try to use for loop but i cost a lot of performance i want proper way to do it
for(int i = 0; i <A.size; i )
{
for(int j=0 ;j <B.size; j )
}
CodePudding user response:
2 loops as you wrote it would mean your code runs the inner bit A * B
times, which you don't want. You want to run it just 'A' times, assuming A and B are equal in size, or max(A.size(), B.size())
times if not.
var out = new ArrayList<Integer>();
for (int i = 0; i < a.size(); i ) {
Integer v = a.get(0);
if (v != null) {
out.add(v);
break;
}
out.add(b.get(0));
}
CodePudding user response:
From my understanding of the question.
Case 1: If both Lists are of equal size then you can use Java stream API two write a consistent code without any loop.
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());
Case 2: If both lists can be of unequal size.
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());