Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of N lists in java

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

like image 500
Abhijeet Kushe Avatar asked Dec 28 '25 17:12

Abhijeet Kushe


2 Answers

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;
}
like image 189
Marco13 Avatar answered Dec 31 '25 06:12

Marco13


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) );
like image 28
Thomas Avatar answered Dec 31 '25 07:12

Thomas