How to Flatten a List of Lists in Java
Table of Contents
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:
JAVAList<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:
JAVAList<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:
JAVAList<Integer> flattenedList = new ArrayList<>();
for (List<Integer> list : listOfLists) {
flattenedList.addAll(list);
}
Alternatively, we could also use a forEach()
loop:
JAVAList<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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- How to deploy a PHP app using Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue