学习计算 Stream 中由指定过滤器表达式传递的匹配项。统计项目,我们可以使用以下两种方法,都是终端操作,结果是一样的。
Stream.count()
Stream.collect(Collectors.counting())
Stream
接口有一个名为 count()
的默认方法,返回一个 $$$
值指示流中匹配项的数量。
long count()
要使用 count() 方法,请在任何 Stream 实例上调用它。
Stream s = ...;
s.count();
//or
s.collect(Collectors.counting());
在此示例中,我们正在计算不同类型流中的元素数量,例如 IntStream
、LongStream
。
long count = Stream.of("how","to","do","in","java").count(); //5
long count = IntStream.of(1,2,3,4,5,6,7,8,9).count(); //9
要计算匹配的项目,我们需要应用过滤器表达式或谓词来过滤以找到匹配的项目,然后我们可以使用 count() API 来计算项目。
在给定的示例中,我们正在计算流中的所有偶数。
long count = LongStream.of(1,2,3,4,5,6,7,8,9)
.filter(i -> i%2 == 0)
.count();
//or
//.collect(Collectors.counting())
快乐学习!!
地址:https://www.cundage.com/article/stream-count-elements-example.html