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
Managing PHP Dependencies with Composer
Getting Started with Electron
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a PHP app using Docker
Getting Started with Sass
Using Puppeteer and Jest for End-to-End Testing
Getting Started with Handlebars.js
Getting User Location using JavaScript's Geolocation API
Setting Up a Local Web Server using Node.js
Using Axios to Pull Data from a REST API
