Java Stream count() 方法

Stream接口有一个名为 count() 的默认方法,它返回一个 long 值,表示流中的项目的数量。

long count()
Java Stream count() 方法

Java Stream count() 方法返回流中元素的数量。
要计算流中元素的数量,我们也可以使用Collectors.counting()方法。

count()方法是一个终端操作。

on  It Road.com

Java Stream count() 示例

Java计算 List流 中元素数量

查看IntStreamLongStream流中的元素数量。

public class Main 
{
	public static void main(String[] args) 
	{
		long count = Stream.of("welcome","to","on","it","road")
					.count();
		System.out.printf( count);

		count = IntStream.of(1,2,3,4,5,6,7,8,9)
					.count();
		System.out.printf( count);

		count = LongStream.of(1,2,3,4,5,6,7,8,9)
					.filter(i -> i%2 == 0)
					.count();
		System.out.printf( count);
	}
}

使用 Collectors.counting() 计算元素数量

Collectors类有一个方法 count()。

它是一个下游收集器。
它接受输入元素并对其进行计数。
如果不存在元素,则计数为“0”。

public class Main 
{
	public static void main(String[] args) 
	{
		long count = Stream.of("welcome","to","on","it","road")
				.collect(Collectors.counting());
		System.out.printf(count);

		count = Stream.of(1,2,3,4,5,6,7,8,9)
				.collect(Collectors.counting());
		System.out.printf(count);

		count = Stream.of(1,2,3,4,5,6,7,8,9)
				.filter(i -> i%2 == 0)
				.collect(Collectors.counting());
		System.out.printf(count);
	}
}
日期:2020-09-17 00:10:04 来源:oir作者:oir