繁体   English   中英

将集合流合并到一个集合中 - Java 8

[英]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> 我只是想不出怎么做。 有任何想法吗?

通过在流上调用flatMap方法可以实现此功能, 该方法采用将Stream项映射到您可以收集的另一个StreamFunction

这里, flatMap方法将Stream<Collection<Long>>转换为Stream<Long> ,并将collect收集到Collection<Long>

Collection<Long> longs = streamOfCollections
    .flatMap( coll -> coll.stream())
    .collect(Collectors.toList());

您可以通过使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM