Search code examples
javaspringlistmergejava-stream

Merge two list together, replace null value of list which is null


I want merging 2 list with these conditions

List<int> A = {1,1,1,null,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 the null value in list A will replace with a value in list B, Also in case there will have a case like 1 , null, 1, null I try to use it for loop but I cost a lot of performance I want a proper way to do it

for(int i = 0; i <A.size; i++) 
{
   for(int j=0 ;j <B.size; j++)

}

Solution

  • 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) v = b.get(0);
      out.add(v);
    }