This post will discuss how to join two Java lists using Plain Java, Java 8, Guava, and Apache Commons Collections.

1. Plain Java

⮚ Using List.addAll()

List interface provides the addAll(Collection) method that appends all elements of the specified collection at the end of the list. We can use it as follows:

We can also initialize the result list by the first list using the ArrayList constructor, thereby preventing an extra call to addAll().

⮚ Double Brace Initialization

We can also use Double Brace Initialization, which internally creates an anonymous inner class with an instance initializer in it.

 
We should best avoid this technique as it costs an extra class at each usage. It also holds hidden references to the enclosing instance and any captured objects. This may cause memory leaks or problems with serialization.

⮚ Using Collections.addAll()

The Collections class provides several useful static utility methods that operate on collections. One such method is addAll(Collection, T[]) that adds all the specified element to the specified collection.

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

2. Using Java 8

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

⮚ Using Stream.of() with flatMap() + Collector

Here we’re obtaining a stream consisting of elements from both the list using the static factory method Stream.of() and accumulating all elements into a new list using a Collector.

⮚ Using Stream.of() with Stream.forEach()

We can avoid using a collector by accumulating all elements using forEach() instead, as shown below:

⮚ Using Stream.concat() + Collector

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

⮚ Using List.addAll()

This is a slight variation of the List.addAll() approach discussed earlier by using streams in Java 8 and above:

3. Using Guava Library

Guava’s Iterables class provides many static utility methods that operate on or return objects of type Iterable.

⮚ Using Iterables.concat()

concat() can be used to combine two iterables into a single iterable.

⮚ Using Iterables.addAll()

addAll() adds all elements in iterable to collection. We can use this in a similar way as Collections’s addAll() method.

4. Using Apache Commons Collections

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

That’s all about joining two lists in Java.

 
Exercise: Concatenate Multiple lists in Java