【问题标题】:Combine stream of Collections into one Collection - Java 8将集合流合并为一个集合 - Java 8
【发布时间】:2015-10-20 19:16:13
【问题描述】:

所以我有一个Stream<Collection<Long>>,我是通过对另一个流进行一系列转换获得的。

我需要做的是将Stream<Collection<Long>> 合并为一个Collection<Long>

我可以将它们全部收集到这样的列表中:

<Stream<Collection<Long>> streamOfCollections = /* get the stream */;

List<Collection<Long>> listOfCollections = streamOfCollections.collect(Collectors.toList());

然后我可以遍历该集合列表以将它们合并为一个。

但是,我想一定有一种简单的方法可以使用.map().collect() 将集合流组合成一个Collection&lt;Long&gt;。我只是想不出该怎么做。有什么想法吗?

【问题讨论】:

  • 查看flatMap

标签: java collections java-8 java-stream


【解决方案1】:

您不需要在不需要时指定类。 更好的解决方案是:

Collection<Long> longs = streamOfCollections.collect(
    ArrayList::new,
    Collection::addAll,
    Collection::addAll
);

比方说,你不需要一个ArrayList而需要一个HashSet,那么你也只需要编辑一行。

【讨论】:

    【解决方案2】:

    您可以通过使用collect 并提供供应商(ArrayList::new 部分)来做到这一点:

    Collection<Long> longs = streamOfCollections.collect(
        ArrayList::new, 
        ArrayList::addAll,
        ArrayList::addAll
    );
    

    【讨论】:

    • @Desik 绝对是 - 这就是我这些天使用的。当时我只是在学习新的流媒体 API。
    • @Desik 为什么它的性能比公认的答案更好?
    • @JordanMackie 因为中间操作较少,也没有创建临时对象。在此解决方案中,您不会在每个集合上都调用 stream()
    【解决方案3】:

    此功能可以通过在流上调用the flatMap method 来实现,它采用FunctionStream 项目映射到另一个您可以收集的Stream

    这里,flatMap 方法将Stream&lt;Collection&lt;Long&gt;&gt; 转换为Stream&lt;Long&gt;collect 将它们收集到Collection&lt;Long&gt;

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

    【讨论】:

    • 您也可以使用方法参考:.flatMap(Collection::stream)
    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2014-11-27
    • 2018-07-17
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    相关资源
    最近更新 更多