Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to merge two Arrays of Classes based on Class variable value

Tags:

java

arrays

Using Java which is the best way to merge two arrays of class based on some value of the class?

Example, We have these two Classes:

public class C1{
  public String id="";
  public String value="";
  public String tot="";
}

public Class C2{
 public String id="";
 public String tot="";
}

And in some point of our code we have two Arrays like:

            //id -value - tot
C1 a [] = { {"1","value#1",""}, 
            {"2","value#2",""}, 
            {"3","value#3",""}, 
            {"4","value#4",""}
    };
                //id - tot
    C2 b [] = { {"1","2"}, 
                {"2","11"}, 
                {"4","15"}
};

The final array should be like:

C1 f [] = { {"1","value#1","2"}, 
            {"2","value#2","11"}, 
            {"3","value#3",""}, 
            {"4","value#4","15"}
};

I'm trying to figure out the best way to achieve this result without reading one or another array from start to end, because here the two arrays have only few rows, but in reality they both can have a length of 100k+...

like image 209
Marcx Avatar asked Nov 05 '22 12:11

Marcx


1 Answers

Put one array in a Map<String, C1> where the key is the id. Iterate through the other array looking for the id in the map and updating the value. If you use a TreeHashMap you can get the values back out in order by the keys.

like image 198
John B Avatar answered Nov 09 '22 05:11

John B