Course contentsShow
← Java
Lesson 1524 of 2,87033. Streams API: Terminal OperationsFree lesson

Using count() to Determine Stream Size

Master the count() method to efficiently calculate the number of elements in a stream after filtering and transformations.

Using count() to Determine Stream Size

You'll learn how to efficiently count stream elements after applying filters and transformations.

What Is count()?

The count() method is a terminal operation that returns the total number of elements in a stream as a long. Think of it as asking "how many items made it through my pipeline?" after all your intermediate operations have run.

Unlike calling .size() on a collection, count() works on the potentially transformed and filtered stream itself—it counts what's left after your operations, not what you started with.

Basic Usage

List<String> names = List.of("Alice", "Bob", "Charlie", "David");

long total = names.stream().count();
// total = 4

Counting After Filtering

The real power emerges when you combine count() with filters and transformations:

long longNames = names.stream()
    .filter(name -> name.length() > 5)
    .count();
// longNames = 2 (Charlie, David)

Counting After Transformations

You can count after map operations to see how many transformed elements exist:

long evenLengthNames = names.stream()
    .map(String::length)
    .filter(len -> len % 2 == 0)
    .count();
// evenLengthNames = 2 (Alice=5? No. Bob=3? No. Actually: Alice=5 odd, Bob=3 odd, Charlie=7 odd, David=5 odd = 0)

Why Use count() Instead of collect().size()?

Using count() is more efficient than collecting to a list and checking size because it doesn't need to store the elements—it just increments a counter as elements flow through.

Key Takeaway:
count() is a terminal operation that returns the number of elements remaining in a stream after all intermediate operations, providing an efficient way to determine stream size without materializing the elements.