Java 8中的收集器counting()方法
在counting()的Java8收藏家类的方法返回类型T的集电极接受元素计数输入元件的数量。
语法如下-
static <T> Collector<T,?,Long> counting()
在这里,参数-
T-输入元素的类型
Long-对象中基本类型为long的此类值
要使用Java中的Collectors类,请导入以下包-
import java.util.stream.Collectors;
以下是counting()在Java8中实现方法的示例-
示例
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("25", "50", "75", "100", "125", "150", "200");
long res = stream.collect(Collectors.counting());
System.out.println("Count of elements in the stream = "+res);
}
}输出结果
Count of elements in the stream = 7