yogev levi yogev levi - 1 month ago 9
Java Question

How do I combination two lists in Java

I have two sets of identical structures. I want to combine them by id field.
The combination should be made on a specific field (for l1 Num2 and for l2 Num1) All other fields should not be changed.

List<MyClass> l1=[{id = 1 , num1 = 3 , num2 = 0 , name = "yoyo"},
{id = 2 , num1 = 9 , num2 = 0 , name = "lolo"},
{id = 3 , num1 = 4 , num2 = 0 , name = "bobo"},
{id = 8 , num1 = 2 , num2 = 0 , name = "toto"}];

List<MyClass> l2=[{id = 1 , num1 = 0 , num2 = 3 , name = "yoyo"},
{id = 2 , num1 = 0 , num2 = 7 , name = "lolo"},
{id = 3 , num1 = 0 , num2 = 8 , name = "bobo"},
{id = 6 , num1 = 0 , num2 = 7 , name = "zozo"}];

// i want to combine the lists to get l3 like this one
list<MyClass> l3=[{id = 1 , num1 = 3 , num2 = 3 , name = "yoyo"},
{id = 2 , num1 = 9 , num2 = 7 , name = "lolo"},
{id = 3 , num1 = 4 , num2 = 8 , name = "bobo"},
{id = 8 , num1 = 2 , num2 = 0 , name = "toto"},
{id = 6 , num1 = 0 , num2 = 7 , name = "zozo"}];

Answer
l3.addall(l1);
for(int i=0;i<l2.size();i++){
   for(int j=0;j<l3.size();j++){
      if(l2.get(i).id!=l3.get(j).id)
          l3.add(l2.get(i);
      else{
         l3.get(j).num2=l2.get(i).num2;
      }
   }
}
Comments