简体   繁体   中英

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

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) );

I am not sure what you mean by best solution but a simple solution would involve using the addAll method.

For extra performance you may also hint the size by summing all sizes.

new ArrayList<...>(totalSizeHere)

Also see this answer: How to do union, intersect, difference and reverse data in java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM