Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn a List of Lists into a List in Java 8?

If I have a List<List<Object>>, how can I turn that into a List<Object> that contains all the objects in the same iteration order by using the features of Java 8?

like image 562
Sarah Szabo Avatar asked Aug 05 '14 19:08

Sarah Szabo


People also ask

How do you make a List of lists in Java?

Given below is the simplest way to create a list of lists in Java: For String: List<List<String>> listOfLists = new ArrayList<>(); That's it.

How do I convert a List from one List to another in Java?

Another approach to copying elements is using the addAll method: List<Integer> copy = new ArrayList<>(); copy. addAll(list); It's important to keep in mind whenever using this method that, as with the constructor, the contents of both lists will reference the same objects.

Can you do a List of a List Java?

Using List.You can declare a List of Lists in Java, using the following syntax. It uses the new operator to instantiate the list by allocating memory and returning a reference to that memory. To add elements to it, call the add() method.

How do you flatten a List in Java?

flatMap() method. The standard solution is to use the Stream. flatMap() method to flatten a List of Lists. The flatMap() method applies the specified mapping function to each element of the stream and flattens it.


1 Answers

You can use flatMap to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:

List<List<Object>> list = ... List<Object> flat =      list.stream()         .flatMap(List::stream)         .collect(Collectors.toList()); 
like image 130
Eran Avatar answered Oct 08 '22 13:10

Eran