假设我有一个列表的列表..
List<List<String>> lists = new ArrayList<>();
有没有巧妙的Lambda方法将其折叠成所有内容的列表?
这就是flatMap的用途:
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());
List<String> result = lists.stream()
.flatMap(l -> l.stream())
.collect(Collectors.toList());
Function.identity()
文档,你是正确的。谢谢! - Dici/*
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());
List::stream
。 - Stuart Marks