count() is a terminal operation that returns the number of elements in a stream as a long. It is most useful after filtering, when you want to know how many elements match a condition.
import java.util.Arrays;
import java.util.List;
public class CountElements {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 15, 8, 49, 25, 98, 98, 32, 15);
long total = list.stream().count();
System.out.println("Total elements: " + total);
long distinct = list.stream().distinct().count();
System.out.println("Distinct elements: " + distinct);
long greaterThan20 = list.stream().filter(n -> n > 20).count();
System.out.println("Greater than 20: " + greaterThan20);
}
}Total elements: 9
Distinct elements: 7
Greater than 20: 5
If asked "Why use count() instead of size()?", explain that size() is better for the whole list. count() shines when combined with other stream operations, such as counting distinct values or values that match a condition.
A concise interview answer is
count() is a terminal operation that returns the number of elements as a long. For a whole list size() is simpler, so I use count() after operations like filter or distinct, for example to count how many values are greater than 20.
Last updated: 11 November 2026
Previous question: Given a list of integers, find the first element using streams.
Next question: Given a list of integers, find the maximum value using streams.