Count the number of elements in the stream using the Java streams counting() method. Following is an example to implement the Java Streams counting() method −
Example
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");
// count
long count = stream.collect(Collectors.counting());
System.out.println("Number of elements in the stream = "+count);
}
}Output
Number of elements in the stream = 5
Let us see another example wherein we have stream of integer elements −
Example
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);
// count
long count = stream.collect(Collectors.counting());
System.out.println("Number of elements in the stream = "+count);
}
}Output
Number of elements in the stream = 6