How to Flatten a List of Lists in Java

Suppose we have a list of lists in Java that we want to flatten.

A nested list might look like this.


We’d like to flatten the list like so:


In Java, a nested list would be represented as a List<List<Integer>> while a flattened list would be a List<Integer>.

Flatten list with Stream’s flatMap()

We can convert the list of lists into a flat list using flatMap() from the Stream API.

Given a nested list:

List<List<Integer>> listOfLists = 

We can easily flatten into a single list.

List<Integer> flatList =

Flatten list with Stream’s collect()

We can avoid flatMap() altogether by performing the aggregation in collect().

List<Integer> flatList =
               .collect(ArrayList::new, List::addAll, List::addAll);

Flatten list without Stream API

We can also avoid the Stream API to avoid creating Stream objects for the elements and the result.

List<Integer> flatList = new ArrayList<>();

For each list in the nested list, we’ll add all the elements into the flatList. This is a concise solution that avoids the Stream API altogether.