Given a list of integers, count the elements using streams.

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.

Key Points

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);
    }
}

Output

Total elements: 9

Distinct elements: 7

Greater than 20: 5

Good to Know

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.

Interview Tip

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.

More Stream API Coding Questions - Level II interview questions

All Stream API Coding Questions - Level II questions