Concatenate Multiple Lists in Java

In this article, several methods to concatenate multiple lists in Java into a single list are discussed using plain Java, Java 8, Guava Library and Apache Commons Collections.

 

1. List.addAll()

List.addAll(Collection) method concatenates all elements of the specified collection to the end of the list. We can use it inside a for-each loop to concatenate multiple lists as shown below:

 

2. Java 8 – Stream.of()

We can also use streams in Java 8 to concatenate multiple lists by obtaining a stream consisting of all elements from every list using static factory method Stream.of() and accumulating all elements into a new list using a Collector.

We can also accumulate all elements using forEach() as shown below:

 

3. Java 8 – Stream.concat()

Stream has concat() method that takes two streams as input and creates a lazily concatenated stream out of them. We can use it to concatenate multiple lists as shown below:

 

4. Guava Iterables Class

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

1. concat() can be used to combine several iterables into a single iterable as shown below.

We can also use ImmutableList.copyOf() in place of Lists.newArrayList() to return an immutable List.

 
2. addAll(Iterable, Collection) adds all elements in specified iterable to collection. We can use it inside a for-each loop to concatenate multiple lists as shown below:

 

5. Apache Commons Collections

Apache Commons Collections ListUtils.union() method takes two lists as an input and returns a new list containing the second list appended to the first list. We can use it to concatenate multiple lists as shown below:

 
Apache Commons Collections also provides IterableUtils class that contains several utility methods for Iterable instances. One such method is chainedIterable(), which can combine multiple Iterables into a single one as shown below:

 

6. Collections.addAll()

Collections class provides addAll(Collection, T[]) method that adds specified elements to the specified collection. This method is similar to List.addAll() but offers better performance.

 

7. Double Brace Initialization

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

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post tt in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz