Java 8 流收集集

2022-01-22 00:00:00 java-8 java java-stream

为了更好地理解新的流 API,我正在尝试转换一些旧代码,但我坚持使用这个.

To better understand the new stream API I'm trying to convert some old code, but I'm stuck on this one.

 public Collection<? extends File> asDestSet() {
    HashMap<IFileSourceInfo, Set<File>> map = new HashMap<IFileSourceInfo, Set<File>>();
    //...
    Set<File> result = new HashSet<File>();
    for (Set<File> v : map.values()) {
        result.addAll(v);
    }
    return result;
}

我似乎无法为其创建有效的收集器:

I can't seem to create a valid Collector for it:

 public Collection<? extends File> asDestSet() {
    HashMap<IFileSourceInfo, Set<File>> map = new HashMap<IFileSourceInfo, Set<File>>();
    //...
    return map.values().stream().collect(/* what? */);
}

推荐答案

使用flatMap:

return map.values().stream().flatMap(Set::stream).collect(Collectors.toSet());

flatMap 将所有集合扁平化为单个流.

The flatMap flattens all of your sets into single stream.

相关文章