Flattening Nested Lists in Java

Learn different ways of converting a List of Lists to a flat List in Java.

Overview

This tutorial demonstrates how to flatten a List containing multiple nested Lists into a flat List. The flattened List must combine all the elements from the nested Lists.

Nested Java Lists

The List in the following snippet contains three nested Lists.

List<List<Integer>> list = List.of(
    List.of(1, 4, 3),
    List.of(12, 17, 14),
    List.of(31, 39, 32)
);Code language: Java (java)

In the next sections, we will flatten the nested List into a flat List containing all the nested Lists elements. The following snippet shows our desired flat List.

[1, 4, 3, 12, 17, 14, 31, 39, 32]Code language: plaintext (plaintext)

Flatten Nested Lists in Java

Using forEach()

One of the simplest ways to flatten a List is to create an empty List and dump it with the elements of all the nested Lists one by one. To do so, we will use the forEach() loop.

Example of flattening a Java nested List using forEach().

List<Integer> output = new ArrayList<>();
list.forEach(output::addAll);

System.out.println(output);
//prints:
//[1, 4, 3, 12, 17, 14, 31, 39, 32]Code language: Java (java)

Using flatMap()

Java Stream’s flatMap() is an Intermediate Stream Operation that applies the given function to each element of the Stream and returns a new Stream consisting of all the resulting Stream elements. Thus, we can use the flatMap() to flatten our Java List.

Example of using Stream flatMap() to flatten a nested Java List.

List<Integer> output = list.stream()
    .flatMap(Collection::stream)
    .toList();

System.out.println(output);
//prints:
//[1, 4, 3, 12, 17, 14, 31, 39, 32]Code language: Java (java)

The function provided to the flatMap() creates Streams for each and every nested List, and the intermediate operation flattens all the Streams to return a single Stream containing all elements. We can then collect the flattened Stream elements into a desired Collection.

Using Guava

Alternatively, we can use the open-source Guava library to flatten a nested Iterable using one of the abstractions provided by the Iterables class. The concat() method allows us to provide an Iterable of Iterables and returns a new Iterable containing elements from all the nested Iterables.

Example of using Guava to flatten a nested List in Java.

List<Integer> output = Lists.newArrayList(
    Iterables.concat(list));
System.out.println(output);
//prints:
//[1, 4, 3, 12, 17, 14, 31, 39, 32]Code language: Java (java)

Summary

This quick tutorial demonstrated several ways of flattening a Java List of nested Lists. Flattening is creating a flat List containing all the elements of all the nested Lists.

The complete source code is available at the GitHub Repository.

More like this: