如何使用lambda表达式将Collapse List<List<String>>转换为List<String>?

7

假设我有一个列表的列表..

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

有没有巧妙的Lambda方法将其折叠成所有内容的列表?
4个回答

15

这就是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());

4
看来您回答了所有flatMap相关的问题。 :-) 需要注意的是,lambda表达式也可以替换为List::stream - Stuart Marks
这个答案非常有用。 - TuGordoBello

2
你可以这样做
List<String> result = lists.stream()
    .flatMap(l -> l.stream())
    .collect(Collectors.toList());

2
不要以为这会起作用——flatMap的参数必须是一个将List<String>转换为Stream<String>的函数。请参阅javadoc - ajb
@ajb:再次查看Function.identity()文档,你是正确的。谢谢! - Dici

0
/*
        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]
    */

-1
List<String> result = lists.stream().flatMap(Collection::stream)
.collect(Collectors.toList());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接