使用Java 8流API将列表列表展平到列表

Twi*_*Twi 3 java java-8 java-stream

我有以下代码,使用Java 8流API可以更简单:

List<List<String>> listOfListValues;
public List<String> getAsFlattenedList() {
        List<String> listOfValues= new ArrayList<>();
        for (List<String> value: listOfListValues) {
            listOfValues.add(String.valueOf(value));
        }
        return listOfValues;
    }
Run Code Online (Sandbox Code Playgroud)

我搜索了SO的解决方案,发现了这个:

listOfListValues.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但这并不是我想要的.

Rol*_*and 7

map这里只需要一个"简单" :

List<List<String>> listOfListValues;
public List<String> getAsFlattenedList() {
    return listOfListValues.stream()
            .map(String::valueOf)
            .collect(toList());
}
Run Code Online (Sandbox Code Playgroud)

flatMap而是用于将一个转换Stream为另一个,如果您需要更多条目或更少当前可用(或者只是新映射Stream到过滤器/ map/etc,它进一步向下),这是有意义的,例如:

  • 计算所有列表的所有唯一字符串:

    listOfListValues.stream()
                    .flatMap(List::stream) // we want to count all, also those from the "inner" list...
                    .distinct()
                    .count()
    
    Run Code Online (Sandbox Code Playgroud)
  • 在特定大小后截断条目:

    listOfListValues.stream()
            .flatMap(list -> {
                if (list.size() > 3) // in this case we use only some of the entries
                    return Stream.concat(list.subList(0, 2).stream(), Stream.of("..."));
                else
                    return list.stream();
            })
            .collect(Collectors.toList());
    
    Run Code Online (Sandbox Code Playgroud)
  • 为几个感兴趣的键平坦化地图的值:

    Map<Key, List<Value>> map = new HashMap<>();
    Stream<Value> valueStream = interestedKeys.stream()
                                              .map(map::get)
                                              .flatMap(List::stream);
    
    Run Code Online (Sandbox Code Playgroud)