How to Flatten a List of Lists in Java

Published Nov 4, 2021

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

A nested list might look like this.

[[1,2,3],[4,5,6],[7,8,9]]

We’d like to flatten the list like so:

[1,2,3,4,5,6,7,8,9]

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 = 
    Collections.singletonList(Arrays.asList(1,2,3));

We can easily flatten into a single list.

List<Integer> flatList = 
    listOfLists.stream()
               .flatMap(List::stream)
               .collect(Collectors.toList());

Flatten list with Stream’s collect()

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

List<Integer> flatList = 
    listOfLists.stream()
               .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<>();
listOfLists.forEach(flatList::addAll);

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.


More Java Articles