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

And*_*ose 30 java collections java-8 java-stream

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

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

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

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

List<Collection<Long>> listOfCollections = streamOfCollections.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

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

但是,我想必须有一种简单的方法将集合流合并为一个或Collection<Long>一个.我只是想不出怎么做.有任何想法吗?.map().collect()

rge*_*man 55

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

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

Collection<Long> longs = streamOfCollections
    .flatMap( coll -> coll.stream())
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用方法引用:`.flatMap(Collection :: stream)` (13认同)

Viv*_*ath 12

您可以通过使用collect和提供供应商(ArrayList::new部件)来实现此目的:

Collection<Long> longs = streamOfCollections.collect(
    ArrayList::new, 
    ArrayList::addAll,
    ArrayList::addAll
);
Run Code Online (Sandbox Code Playgroud)

  • 比使用flatMap()的解决方案更高效的解决方案 (2认同)
  • @JordanMackie因为中间操作较少,并且没有创建临时对象.在这个解决方案中,你不要在每个集合上调用`stream()`. (2认同)