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 ?
In Java, we can use String. join(",", list) to join a List String with commas.
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.
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.
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());
You can do
List<String> result = lists.stream()
.flatMap(l -> l.stream())
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With