使用Java streamcounting()
方法对流中的元素数进行计数。以下是实现Java Streamscounting()
方法的示例-
import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("Kevin", "Jofra","Tom", "Chris", "Liam"); //数 long数 = stream.collect(Collectors.counting()); System.out.println("Number of elements in the stream = "+count); } }
输出结果
Number of elements in the stream = 5
让我们看看另一个例子,其中我们有整数元素流-
import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<Integer> stream = Stream.of(5, 10, 20, 40, 80, 160); //数 long数 = stream.collect(Collectors.counting()); System.out.println("Number of elements in the stream = "+count); } }
输出结果
Number of elements in the stream = 6