Java Stream count()方法及实例
long count() 返回流中元素的数量。这是 还原 操作的一个特例(还原操作需要一连串的输入元素,并通过重复应用合并操作将它们合并成一个单一的汇总结果)。这是一个 终端操作 ,也就是说,它可以遍历流,产生一个结果或副作用。在执行终端操作后,流管道被认为已被消耗,不能再被使用。
语法:
long count()
注意: 计数操作的返回值是流中元素的数量。
例1: 计算数组中的元素数量。
// Java code for Stream.count()// to count the elements in the stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list of Integers List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10, 12); // Using count() to count the number // of elements in the stream and // storing the result in a variable. long total = list.stream().count(); // Displaying the number of elements System.out.println(total); }}
输出:
7
例2: 计算一个列表中不同元素的数量。
// Java code for Stream.count()// to count the number of distinct// elements in the stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list of Strings List<String> list = Arrays.asList("GFG", "Geeks", "for", "Geeks", "GeeksforGeeks", "GFG"); // Using count() to count the number // of distinct elements in the stream and // storing the result in a variable. long total = list.stream().distinct().count(); // Displaying the number of elements System.out.println(total); }}输出:
4
