Stream count() method in Java with examples

Last Updated : 26 Dec, 2025

Stream.count() method returns the number of elements in a stream. It is a terminal operation and a special case of reduction, which combines a sequence of elements into a single summary result. After performing count(), the stream is consumed and cannot be reused.

  • Returns the total number of elements in the stream.
  • Can be combined with intermediate operations like distinct(), filter(), etc.
  • Consumes the stream once executed.

Example:

Java
import java.util.*;
class GFG {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10, 12);
        long total = list.stream().count();
        System.out.println(total);
    }
}

Output
7

Explanation:

  • Converts the list into a stream using list.stream().
  • count() returns the total number of elements.

Syntax

long count()

  • Parameters: This method does not take any parameters.
  • Return Value: Returns a long representing the number of elements in the stream.

Example: This code shows how to count unique elements in a stream using distinct() with count().

Java
import java.util.*;
class GFG {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("GFG", "Geeks", "for", "Geeks", "GeeksforGeeks", "GFG");
        long total = list.stream().distinct().count();

        System.out.println(total);
    }
}

Output
4

Explanation:

  • distinct() removes duplicate elements from the stream.
  • count() returns the total number of remaining elements in the stream.
Comment