In this tutorial, we will see how to get Stream count in Java 8 using Stream count and Collector counting methods.
How to get Stream count:
We can find the number of elements in a stream using two different methods. count() method from Stream class and Collectors.counting() static method from Collectors class.
Syntax:
Syntax- Stream count()
long count()
Returns the count of elements in the stream. If no elements are present, the result is 0.
Syntax- Collectors.counting()
public static <T> Collector<T,?,Long> counting()
Returns a Collector accepting elements of type T that counts the number of input elements. If no elements are present, the result is 0.
Get Stream count – count():
Getting the Stream count using Stream’s count() method.
StreamCount.java
import java.util.stream.Stream;
public class StreamCount {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
System.out.println("Stream Count is: "+stream.count());
}
}
Output:
Terminal
Stream Count is: 9
Stream count on the filter:
We can also get the count of a stream on applying the filter condition.
StreamCount.java
import java.util.stream.Stream;
public class StreamCount {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
Long count = stream.filter(num->(num%2)==0).count();
System.out.println("There are "+count+" even numbers in the Stream");
}
}
Output:
Terminal
There are 4 even numbers in the Stream
Get Stream Count – Collectors counting:
Collectors counting is a static method used to calculate the elements in a stream. If there are no elements in a Stream, it returns merely ‘0’ as a result.
StreamCount.java
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamCount {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
Long count = stream.collect(Collectors.counting());
System.out.println("Stream Count: "+count);
}
}
Output:
Terminal
Stream Count: 6
Done!
Happy Learning 🙂