What is the best way to create a union of N lists in java ?
For eg
List<Integer> LIST_1 = Lists.newArrayList(1);
List<Integer> LIST_2 = Lists.newArrayList(2);
List<Integer> LIST_3 = Lists.newArrayList(3);
List<Integer> LIST_4 = Lists.newArrayList(4);
List<Integer> LIST_1_2_3_4 = Lists.newArrayList(1,2,3,4);
assert LIST_1_2_3_4.equals(union(LIST_1,LIST_2,LIST_3,LIST_4));
The union method will take a var args parameter
<Item> List<Item> union(List<Item> ... itemLists)
Is there a library which provides this method.Simplest way is to loop through the array and accumulate each list into one
There may be a library, but including it only for these 3 lines of code would probably not worth another dependency...
private static <Item> List<Item> union(List<Item> ... itemLists)
{
List<Item> result = new ArrayList<Item>();
for (List<Item> list : itemLists) result.addAll(list);
return result;
}
You could use Google Guava:
List<Integer> joined = new ArrayList<>( Iterables.concat(LIST_1, LIST_2, LIST_3, LIST_4) );
or for comparison only:
Iterables.elementsEqual( LIST_1_2_3_4, Iterables.concat(LIST_1, LIST_2, LIST_3, LIST_4) );
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