【发布时间】:2018-10-09 17:31:59
【问题描述】:
以下 lambda 在 Java 中是否可能以某种方式出现?我想计算过滤流中的元素,但同时存储前 10 个
stream().filter(myFilter) //Reduces input to forthcoming operations
.limit(10) //Limits to ten the amount of elements to finish stream
.peek(myList::add) //Stores the ten elements into a list
.count(); //Here is the difficult one. Id like to count everything the total of elements that pass the filter, beyond the 10 I am fetching
编辑:在我看来这太含蓄了,但这个想法当然是一种潜在的解决方案,它会是最快的(比调用两次流生成器并分别在最少):
List<Entity> entities = stream().filter(myFilter)
.limit(10)
.collect(Collectors.toList());
long entitiesCount = stream().filter(myFilter)
.count();
...从一次迭代中获利,而不必将整个集合加载到内存中。我正在对答案进行并行化测试
【问题讨论】:
-
您可以使用 2 个单独的流来实现。
-
这是一个流,因为它是一个非常昂贵(长时间)的迭代......这是我这种疯狂想法的唯一意义
-
如果流很大,最好的处理方式是看能不能并行化。如果这必须是一个顺序操作,正如这里和here 所指出的那样,也许最好避免使用 API 玩游戏并使用一个很好的旧
.forEach() -
@FedericoPeraltaSchaffner 我认为在这种情况下自定义收集器将是答案,无论来源是什么......
-
@FedericoPeraltaSchaffner 当然,但是在那个计数中,有很多易失性写入和读取,你必须衡量哪个才是赢家......当然,我会选择收集器
标签: java lambda java-stream