且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Java 8流API将列表的列表展平为列表

更新时间:2023-10-05 15:02:28

在这里您只需要简单" map:

You require only a "simple" map here:

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

flatMap而是用于将一个Stream转换为另一个Stream,这在您需要比当前可用的条目更多或更少的条目时有意义(或者仅是新映射的Stream对其进行向下过滤/映射/等操作)是有道理的,例如:

flatMap is rather used to transform one Stream to another, which makes sense if you need more entries or less then currently available (or just a newly mapped Stream to filter/map/etc it further down), e.g.:

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

  • count all the unique strings of all lists:

listOfListValues.stream()
                .flatMap(List::stream) // we want to count all, also those from the "inner" list...
                .distinct()
                .count()

  • 在一定大小后截断条目:

  • truncate entries after a certain size:

    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());
    

  • 为多个感兴趣的键展平地图的值:

  • flattening values of a map for several interested keys:

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