Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapse List<List<String>> into List<String> using a lambda?

Say I have a list of Lists..

List<List<String>> lists = new ArrayList<>();

Is there a clever lambda way to collapse this into a List of all the contents ?

like image 886
Hydrosan Avatar asked Sep 19 '14 19:09

Hydrosan


People also ask

How do you combine a List of strings in Java?

In Java, we can use String. join(",", list) to join a List String with commas.

How do you flatten a stream List?

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.

How do you convert a List of strings to one string in Java?

Using StringBufferCreate an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.


2 Answers

That's what flatMap is for :

List<String> list = inputList.stream() // create a Stream<List<String>>
                             .flatMap(l -> l.stream()) // create a Stream<String>
                                                       // of all the Strings in
                                                       // all the internal lists
                             .collect(Collectors.toList());
like image 61
Eran Avatar answered Oct 20 '22 08:10

Eran


You can do

List<String> result = lists.stream()
    .flatMap(l -> l.stream())
    .collect(Collectors.toList());
like image 44
Dici Avatar answered Oct 20 '22 09:10

Dici