Java 8 Streams:计算进入终端操作的所有元素 [英] Java 8 Streams: count all elements which enter the terminal operation

查看:43
本文介绍了Java 8 Streams:计算进入终端操作的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好(或只是另一种)方法来获取进入流的终端操作的所有项目的计数,而不是以下方法:

I wonder whether there is a nicer (or just an other) approach to get the count of all items that enter the terminal operation of a stream instead of the following:

Stream<T> stream = ... // given as parameter
AtomicLong count = new AtomicLong();
stream.filter(...).map(...)
      .peek(t -> count.incrementAndGet())

其中count.get()给出了该阶段已处理项目的实际计数.

where count.get() gives me the actual count of the processed items at that stage.

我故意跳过了终端操作,因为这可能会在.forEach.reduce.collect之间改变. 我确实知道 .count ,但是似乎只有当我将.forEach.map交换并将.count用作终端操作时,它才能很好地工作.但是在我看来,然后.map被滥用了.

I deliberately skipped the terminal operation as that might change between .forEach, .reduce or .collect. I do know .count already, but it seems to work well only if I exchange a .forEach with a .map and use the .count as terminal operation instead. But it seems to me as if .map is then misused.

我对上述解决方案的真正不满意之处是:如果在其后添加一个过滤器,它只会计算该特定阶段的元素,而不是用于终端操作的元素.

What I don't really like with the above solution: if a filter is added after it, it just counts the elements at that specific stage, but not the ones that are going into the terminal operation.

我想到的另一种方法是将已过滤和映射的值collect放入列表中并对其进行操作,只需调用list.size()即可获取计数.但是,如果流的收集会导致错误,那么这将行不通,而如果使用了适当的try/catch,则使用上述解决方案,我可以对到目前为止的所有已处理项目进行计数.但是,这并不是一个硬性要求.

The other approach that comes to my mind is to collect the filtered and mapped values into a list and operate on that and just call list.size() to get the count. However this will not work, if the collection of the stream would lead to an error, whereas with the above solution I could have a count for all processed items so far, if an appropriate try/catch is in place. That however isn't a hard requirement.

推荐答案

在终端操作IMO之前,您似乎已经通过peek通过了最干净的解决方案.我可能认为需要这样做的唯一原因是出于调试目的-如果是这种情况,则为此专门设计了peek.为此,包装Stream并提供单独的实现实在太多了-除了大量的时间和以后对Streams中添加的所有内容的支持之外.

It seems you already have the cleanest solution via peek before the terminal operation IMO. The only reason I could think that this is needed is for debug purposes - and if that is the case, than peek was designed for that. Wrapping the Stream for that and providing separate implementations is way too much - besides the huge amount of time and later support for everything that get's added to Streams.

对于如果添加了另一个过滤器,该怎么做?那么,提供一个代码注释(我们很多人这样做)和一些否则会失败的测试用例.

For the part of what if there is another filter added? Well, provide a code comment(lots of us do that) and a few test cases that would otherwise fail for example.

我的0.02美元

这篇关于Java 8 Streams:计算进入终端操作的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆