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!
Getting Started with Svelte
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
How to Serve Static Files with Nginx and Docker
How to deploy a .NET app using Docker
How to deploy a PHP app using Docker
Getting Started with Deno
How to deploy an Express app using Docker
Getting Started with Sass
Learn how to use v-model with a custom Vue component
Building a Real-Time Note-Taking App with Vue and Firebase
Setting Up Stylus CSS Preprocessor
