将集合流合并为一个集合 - Java 8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31706699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:01:43  来源:igfitidea点击:

Combine stream of Collections into one Collection - Java 8

javacollectionsjava-8java-stream

提问by Andrew Mairose

So I have a Stream<Collection<Long>>that I obtain by doing a series of transformations on another stream.

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

What I need to do is collect the Stream<Collection<Long>>into one Collection<Long>.

我需要做的是将其收集Stream<Collection<Long>>到一个Collection<Long>.

I could collect them all into a list like this:

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

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

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

And then I could iterate through that list of collections to combine them into one.

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

However, I imagine there must be a simple way to combine the stream of collections into one Collection<Long>using a .map()or .collect(). I just can't think of how to do it. Any ideas?

但是,我想一定有一种简单的方法可以Collection<Long>使用 a .map()or将集合流合并为一个.collect()。我只是想不出该怎么做。有任何想法吗?

回答by rgettman

This functionality can be achieved with a call to the flatMapmethodon the stream, which takes a Functionthat maps the Streamitem to another Streamon which you can collect.

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

Here, the flatMapmethod converts the Stream<Collection<Long>>to a Stream<Long>, and collectcollects them into a Collection<Long>.

在这里,该flatMap方法将 转换Stream<Collection<Long>>为 a Stream<Long>,并将collect它们收集到 a 中Collection<Long>

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

回答by Vivin Paliath

You could do this by using collectand providing a supplier (the ArrayList::newpart):

您可以通过使用collect和提供供应商(ArrayList::new零件)来做到这一点:

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

回答by Helmut Provost

You don't need to specify classes when not needed. A better solution is:

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

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

Say, you don't need an ArrayList but need a HashSet, then you also need to edit only one line.

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