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方法可以实现此功能,该方法Function将Stream项目映射到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)
Viv*_*ath 12
您可以通过使用collect和提供供应商(ArrayList::new部件)来实现此目的:
Collection<Long> longs = streamOfCollections.collect(
ArrayList::new,
ArrayList::addAll,
ArrayList::addAll
);
Run Code Online (Sandbox Code Playgroud)