This post will discuss how to join multiple lists in Java. The solution creates a new list containing all elements of the provided lists, in iteration order.

1. Using Stream.flatMap() method

You can easily join multiple lists with the help of the flatMap() method provided by Java 8 Stream API. The idea is to create a stream of lists, and flatten each list using the flatMap() method, and finally collect the elements in a new list. This is demonstrated below:

Download  Run Code

Output:

[C, C++, C#, Java, Kotlin, Ruby, JavaScript]

 
Since the Stream.of() method uses varargs, you can create a generic utility method to concat an arbitrary number of lists.

Download  Run Code

Output:

[C, C++, C#, Java, Kotlin, Ruby, JavaScript]

 
Note that Stream.of() is just a wrapper over Arrays.stream(), and both methods can be used interchangeably except for the primitive arrays:

Download  Run Code

2. Using List.addAll() method

A straightforward solution is to create a new list, and add all the elements in each list to the end of this list using the addAll() method. This can be done using a simple for loop, as shown below:

Download  Run Code

Output:

[C, C++, C#, Java, Kotlin, Ruby, JavaScript]

 
Here’s an equivalent version using the Stream API. It takes advantage of the forEach() method.

Download  Run Code

Output:

[C, C++, C#, Java, Kotlin, Ruby, JavaScript]

3. Using Stream.concat() method

If you want to join only two lists, you can use the Stream.concat() method. The idea is to get a stream of elements from both lists and pass each stream to the Stream.concat() method. It creates a lazily concatenated stream whose elements are all the elements of the first stream, followed by all the elements of the second stream.

Download  Run Code

Output:

[C, C++, Java, Kotlin]

4. Using Apache Commons Collections

Apache Commons Collections ListUtils.union() method returns a new list containing the concatenation of the provided lists. You can use it to join two lists, as shown below:

Download Code

Output:

[C, C++, Java, Kotlin]

That’s all about joining multiple lists in Java.