How to Flatten a List of Lists in Java

Updated onbyAlan Morel
How to Flatten a List of Lists in Java

Lists in Java can hold any data type you want it to, including other lists.

This means that you can have a list of lists, which is called a nested list.

When you want to turn a nested list to a single list, it is called flattening the list.

In this post, we'll learn how to flatten a list of lists in Java.

How to Flatten a List of Lists in Java

To start, let's define a list of list of integers, and fill it with example values:

JAVA
List<List<Integer>> listOfLists = new ArrayList<>(); listOfLists.add(Arrays.asList(1, 2, 3)); listOfLists.add(Arrays.asList(4, 5, 6)); listOfLists.add(Arrays.asList(7, 8, 9));

This makes the list look something like:

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

We want the list to look like this after we flatten it:

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

The easiest way to flatten this list is to use the flatMap() method:

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

The flatMap() method takes a function as an argument, and applies that function to each element in the list, and in our case, we are using List::stream, then using the collect() method to collect the results into a list.

In a more traditional way, we can use a for loop to flatten the list:

JAVA
List<Integer> flattenedList = new ArrayList<>(); for (List<Integer> list : listOfLists) { flattenedList.addAll(list); }

Alternatively, we could also use a forEach() loop:

JAVA
List<Integer> flattenedList = new ArrayList<>(); listOfLists.forEach(flattenedList::addAll);

Conclusion

In this post, we learned how to flatten a list of lists in Java.

You have several options at your disposal, including using the flatMap() method, a for loop, or a forEach() loop.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.