Java – Combine Multiple Collections – Java – 合并多个集合

最后修改: 2016年 12月 18日


1. Overview


In this tutorial, we will illustrate how to concatenate multiple collections into one logical collection.


We’ll be exploring five different approaches – two using Java 8, one using Guava, one using Apache Commons Collections, and one using only the standard Java 7 SDK.

我们将探索五种不同的方法–两种使用Java 8,一种使用Guava,一种使用Apache Commons Collections,还有一种只使用标准的Java 7 SDK。

In the examples that follow, let’s consider the following collections:


Collection<String> collectionA = Arrays.asList("S", "T");
Collection<String> collectionB = Arrays.asList("U", "V");

2. Using Java 8 Stream API

2.使用Java 8的Stream API

The Stream interface in Java API provides useful methods that make it easier to process collections. Let’s take a look at two of its methods – concat() and flatMap() – that are used for combining collections.

Java API中的Stream接口提供了有用的方法,使处理集合更加容易。让我们来看看其中的两个方法–concat()flatMap()–用于组合集合。

Once you obtain a Stream, you can perform aggregate operations on it.


2.1. Using the concat() Method


The static method concat() combines two Streams logically by creating a lazily concatenated Stream whose elements are all the elements of the first Stream followed by all the elements of the second Stream.


In the below example, let’s combine collectionA and collectionB using the concat() method:


Stream<String> combinedStream = Stream.concat(,;

If you need to combine more than two Streams, you can invoke the concat() method again from within the original invocation:


Stream<String> combinedStream = Stream.concat(

It is important to note that Java 8 Streams are not reusable, so you should take this into consideration when assigning them to variables.

需要注意的是,Java 8的Streams是不可重用的,所以你在将它们分配给变量时应该考虑到这一点。

2.2. Using the flatMap() Method

2.2.使用flatMap() 方法

The flatMap() method returns a Stream after replacing each element of this Stream with the contents of a mapped Stream that is produced by applying the provided mapping function to each element.


The example below demonstrates merging of collections using the flatMap() method. Initially, you get a Stream whose elements are the two collections, and then you flatten the Stream before collecting it into a merged list:


Stream<String> combinedStream = Stream.of(collectionA, collectionB)
Collection<String> collectionCombined = 

3. Using Guava


The Guava library from Google provides several convenience methods for operating on collections and can be used with Java 6 or later.

来自Google的Guava库提供了几种操作集合的便利方法,可以在Java 6或更高版本中使用。

3.1. Using the Iterables.concat() Method


The Iterables.concat() method is one of the Guava convenient methods that is used for merging collections:


Iterable<String> combinedIterables = Iterables.unmodifiableIterable(
  Iterables.concat(collectionA, collectionA));

The Iterable that is returned can be converted into a collection:


Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);

3.2. Maven Dependency


Add the following dependency to your Maven pom.xml file to include the Guava library in your project:



You can find the latest version of the Guava library in the Maven Central repository.

您可以在Maven Central资源库中找到Guava库的最新版本。

4. Using Apache Commons Collections

4.使用Apache Commons集合

Apache Commons Collections is yet another library of utilities that assist in working with the various collections. The library provides two utility methods that can be used for combining collections. In this section, let us understand how these methods work.

Apache Commons Collections是另一个协助处理各种集合的实用程序库。该库提供了两种实用的方法,可用于组合集合。在本节中,让我们了解这些方法是如何工作的。

4.1. Using the IterableUtils.chainedIterable() Method


The IterableUtils class provides utility methods and decorators for Iterable instances. It provides the the chainedIterable() method, which can be used to combine multiple Iterables into a single one.


Iterable<String> combinedIterables = IterableUtils.chainedIterable(
  collectionA, collectionB);

4.2. Using the CollectionUtils.union() Method


Utility methods and decorators for Collection instances are provided by the CollectionUtils class. The union() method from this class returns a Collection containing the union of the given Iterable instances.


Iterable<String> combinedIterables = CollectionUtils.union(
  collectionA, collectionB);

In the case of the union() method, the cardinality of each element in the returned collection will be equal to the maximum of the cardinality of that element in the two given Iterables. This means that the combined collection only consists of the elements in the first collection and the elements in the second collection that were not present in the first one.


4.3. Maven Dependency


Add the following dependency to your Maven pom.xml file to include the Apache Commons Collections library in your project:

在你的Maven pom.xml文件中添加以下依赖,以便在项目中加入Apache Commons集合库。


You can find the latest version of the Apache Commons library in the Maven Central repository.

您可以在Maven Central资源库中找到最新版本的Apache Commons库。

5. Using Java 7

5.使用Java 7

If you are still using Java 7 and wish to avoid third party libraries such as Guava, you can use the addAll() method to combine elements from multiple collections, or you can write your own utility methods to combine Iterables.

如果你还在使用Java 7,并希望避免使用第三方库,如Guava,你可以使用addAll()方法来组合多个集合中的元素,或者你可以编写自己的实用方法来组合Iterables

5.1. Using the addAll() Method


Of course the simplest solution for combining collections is using the addAll() method, as in the following List example, however it is worth noting that this method creates a new collection with additional references to the same objects that are in the first two collections:


List<String> listC = new ArrayList<>();

5.2. Writing a Custom concat() Method


The below example defines a concat() method that accepts two Iterables and returns a merged Iterable object:


public static <E> Iterable<E> concat(
  Iterable<? extends E> i1,
  Iterable<? extends E> i2) {
        return new Iterable<E>() {
            public Iterator<E> iterator() {
                return new Iterator<E>() {
                    Iterator<? extends E> listIterator = i1.iterator();
                    Boolean checkedHasNext;
                    E nextValue;
                    private boolean startTheSecond;

                    void theNext() {
                        if (listIterator.hasNext()) {
                            checkedHasNext = true;
                            nextValue =;
                        } else if (startTheSecond)
                            checkedHasNext = false;
                        else {
                            startTheSecond = true;
                            listIterator = i2.iterator();

                    public boolean hasNext() {
                        if (checkedHasNext == null)
                        return checkedHasNext;

                    public E next() {
                        if (!hasNext())
                            throw new NoSuchElementException();
                        checkedHasNext = null;
                        return nextValue;

                    public void remove() {

The concat() method can be invoked by passing the two collections as its arguments:


Iterable<String> combinedIterables = concat(collectionA, collectionB);
Collection<String> collectionCombined = makeListFromIterable(combinedIterables);

If you need the Iterable to be available as a List, you can also use the makeListFromIterable() method that creates a List using the members of the Iterable:


public static <E> List<E> makeListFromIterable(Iterable<E> iter) {
    List<E> list = new ArrayList<E>();
    for (E item : iter) {
    return list;

6. Conclusion


The article discussed several different ways to combine two collections logically in Java without creating additional references to the objects they contain.


The code for this tutorial is available over on Github.