所以我有一个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<Long>中。我就是想不出该怎么做。有什么想法吗?
发布于 2015-07-30 01:04:22
此功能可以通过调用流上的the flatMap method来实现,该调用接受一个Function,该call将Stream项映射到您可以收集的另一个Stream。
在这里,flatMap方法将Stream<Collection<Long>>转换为Stream<Long>,collect将它们收集到Collection<Long>中。
Collection<Long> longs = streamOfCollections
.flatMap( coll -> coll.stream())
.collect(Collectors.toList());发布于 2015-07-30 01:10:58
您可以通过使用collect并提供一个供应商( ArrayList::new部件)来完成此操作:
Collection<Long> longs = streamOfCollections.collect(
ArrayList::new,
ArrayList::addAll,
ArrayList::addAll
);发布于 2019-03-27 19:38:00
在不需要的时候,你不需要指定类。更好的解决方案是:
Collection<Long> longs = streamOfCollections.collect(
ArrayList::new,
Collection::addAll,
Collection::addAll
);比方说,您不需要ArrayList,但需要HashSet,那么您也只需要编辑一行。
https://stackoverflow.com/questions/31706699
复制相似问题