[英]Combine stream of Collections into one Collection - Java 8
所以我有一个Stream<Collection<Long>>
,我通过在另一个流上进行一系列转换获得。
我需要做的是将Stream<Collection<Long>>
Collection<Long>
到一个Collection<Long>
。
我可以将它们全部收集到这样的列表中:
<Stream<Collection<Long>> streamOfCollections = /* get the stream */;
List<Collection<Long>> listOfCollections = streamOfCollections.collect(Collectors.toList());
然后我可以遍历该集合列表,将它们合并为一个集合。
但是,我想必须有一种简单的方法,使用.map()
或.collect()
将集合流合并到一个Collection<Long>
。 我只是想不出怎么做。 有任何想法吗?
您可以通过使用collect
并提供供应商( ArrayList::new
部分)来完成此操作:
Collection<Long> longs = streamOfCollections.collect(
ArrayList::new,
ArrayList::addAll,
ArrayList::addAll
);
不需要时,您不需要指定类。 更好的解决方案是:
Collection<Long> longs = streamOfCollections.collect(
ArrayList::new,
Collection::addAll,
Collection::addAll
);
比如,您不需要ArrayList但需要HashSet,那么您还需要只编辑一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.