10 Ways to Join Two Lists in Java

This article discusses how to join two Java lists using Plain Java, Java 8, Guava, and Apache Commons Collections.

1. Pure Java

useList.addAll()

ListThe interface provides addAll(Collection)methods to append all elements of the specified collection to the end of the list. We can use it as follows:

// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    
    
    List<T> list = new ArrayList<>();
 
    list.addAll(list1);
    list.addAll(list2);
 
    return list;
}

We can also initialize the result list constructor with the first list ArrayList, preventing an extra call addAll().

// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    
    
    List<T> list = new ArrayList<>(list1);
    list.addAll(list2);
 
    return list;
}     

Double brace initialization

We can also use double brace initialization which internally creates an anonymous inner class which contains an instance initializer.

// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    
    
    return new ArrayList<T>() {
    
    {
    
    
            addAll(list1);
            addAll(list2);
        }};
}

We're better off avoiding this technique because it costs an extra class every time we use it. It also contains hidden references to the enclosing instance and any captured objects. This can cause memory leaks or serialization issues.

useCollections.addAll()

This Collectionsclass provides several useful static utility methods that operate on collections. One such method is addAll(Collection, T[])to add all specified elements to the specified collection.

// 在 Java 中连接两个列表的方法
public static List<String> merge(List<String> list1, List<String> list2)
{
    
    
    List<String> list = new ArrayList<>();
 
    Collections.addAll(list, list1.toArray(new String[0]));
    Collections.addAll(list, list2.toArray(new String[0]));
 
    return list;
}

This method is similar to List.addAll()but may run faster.

2. Using Java 8

We can also use Java 8 Stream to join two lists.

use Stream.of()andflatMap()

Here we've taken a stream of elements from both lists using a static factory method Stream.of()and accumulated all the elements into a new list using a Collector .

// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    
    
    return Stream.of(list1, list2)
                .flatMap(x -> x.stream())
                .collect(Collectors.toList());
}

use Stream.of()andStream.forEach()

We can avoid using a collector by accumulating all elements forEach()instead, like so:

// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    
    
    List<T> list = new ArrayList<>();
    Stream.of(list1, list2).forEach(list::addAll);
 
    return list;
}

useStream.concat()

Java Stream provides concat()It takes two streams as input and creates a lazily joined stream whose elements are all elements of the first stream followed by all elements of the second stream.

// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    
    
    return Stream.concat(list1.stream(), list2.stream())
                .collect(Collectors.toList());
}

useList.addAll()

Here's a slight variation on the List.addAll()previously discussed method of using streams in Java 8 and later:


// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    
    
    List<T> list = list1.stream().collect(Collectors.toList());
    list.addAll(list2);
 
    return list;
}

3. Using the Guava library

Guava's Iterablesclasses provide a number of static utility methods for manipulating or returning objects of a type Iterable.

useIterables.concat()

concat()Can be used to combine two iterables into one iterable.


// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2) {
    
    
    return Lists.newArrayList(Iterables.concat(list1, list2));
}

useIterables.addAll()

addAll()Adds all elements of the iterable to the collection. We can use its methods in a similar way to Collections addAll().

// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    
    
    List<T> list = Lists.newArrayList();
 
    Iterables.addAll(list, list1);
    Iterables.addAll(list, list2);
 
    return list;
}

4. Using Apache Commons collections

The Apache Commons Collections ListUtilsclass provides union()a method that takes two lists as input and returns a new list containing the second list appended to the first.

// Java 中连接两个列表的通用方法
public static<T> List<T> merge(List<T> list1, List<T> list2) {
    
    
    return ListUtils.union(list1, list2);
}

That's all there is to joining two lists in Java.

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/132137369