This post will discuss how to flatten a List of Lists in Java. In other words, convert a List<List<T>> into a List<T> in Java.

1. Using Stream.flatMap() method

The standard solution is to use the Stream.flatMap() method to flatten a List of Lists. The flatMap() method applies the specified mapping function to each element of the stream and flattens it.

The following program demonstrates the usage of the flatMap() method to flatten a list of lists:

Download  Run Code

Output:

Original List [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

2. Using foreach construct

You don’t need fancy Streams to perform this challenging-looking task. Another alternative is to use a foreach-construct to add elements of each list into a new list, as demonstrated below:

Download  Run Code

Output:

Original List [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

 
This is equivalent to the following Java 8 code using forEach() method:

Download  Run Code

Output:

Original List [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

3. Using Stream.collect() method

Another Java 8 solution is to perform a mutable reduction operation on the elements of the stream using the collect() method. For example,

Download  Run Code

Output:

Original List [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

4. Using Stream.reduce() method

Another possibility is to perform a reduction operation on the elements of the stream using an associative accumulation function:

Download  Run Code

Output:

Original List [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

 
Here’s a better way to do it, using the provided identity value and an associative accumulation function.

Download  Run Code

Output:

Original List [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Flattened List [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

That’s all about flattening a List of Lists in Java.