【发布时间】:2015-05-26 17:16:46
【问题描述】:
为了更好地理解新的流 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;
}
我似乎无法为其创建有效的收集器:
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());或.collect(toCollection(HashSet::new));因为toSet()返回的集合实现背后没有保证。 -
或
.collect(HashSet::new, Set::addAll, Set::addAll)
标签: java java-8 java-stream