Java 8 流收集集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30464953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:41:28  来源:igfitidea点击:

Java 8 Stream Collecting Set

javajava-8java-stream

提问by molok

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

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

 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? */);
}

采纳答案by Tagir Valeev

Use flatMap:

使用flatMap

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

The flatMapflattens all of your sets into single stream.

flatMap您的所有集合展平为单个流。