本文介绍了Java 8流收集集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了更好地理解我正在尝试转换一些旧代码的新流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? */);
}
推荐答案
使用 :
return map.values().stream().flatMap(Set::stream).collect(Collectors.toSet());
flatMap
将所有集合展平为单流。
The flatMap
flattens all of your sets into single stream.
这篇关于Java 8流收集集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!