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+...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With