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 ?
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 ?
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());
flatMap
has to be a function that turns a List<String>
into a Stream<String>
. See the javadoc. –
Mesopotamia Function.identity()
doc, you are right. Thanks ! –
Unwish /*
Let's say you have list of list of person names as below
[[John, Wick], [Patric, Peter], [Nick, Bill]]
*/
List<List<String>> personsNames =
List.of(List.of("John", "Wick"), List.of("Patric", "Peter"), List.of("Nick", "Bill"));
List<String> finalList = personsNames
.stream()
.flatMap(name -> name.stream()).collect(toList());
/*
* Final result will be like - [John, Wick, Patric, Peter, Nick, Bill]
*/
List<String> result = lists.stream().flatMap(Collection::stream)
.collect(Collectors.toList());
© 2022 - 2024 — McMap. All rights reserved.
List::stream
. – Kurtzig