Java 8 Stream Collecting Set

﹥>﹥吖頭↗ 提交于 2019-12-31 08:42:08

问题


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

回答1:


Use flatMap:

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

The flatMap flattens all of your sets into single stream.



来源:https://stackoverflow.com/questions/30464953/java-8-stream-collecting-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!