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:
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:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
We want the list to look like this after we flatten it:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
The easiest way to flatten this list is to use the flatMap()
method:
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:
List<Integer> flattenedList = new ArrayList<>();
for (List<Integer> list : listOfLists) {
flattenedList.addAll(list);
}
Alternatively, we could also use a forEach()
loop:
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on X! You can also join the conversation over at our official Discord!
Leave us a message!