Count Elements

count() is a Stream API terminal operation that returns the number of elements remaining in the stream after any intermediate operations like filter have been applied.

Key Points: • count() is a terminal operation, so it triggers stream execution and returns a long. • It's typically preceded by filter() to count only elements matching a condition. • For simple size counting without filtering, count() still works but collection.size() is more efficient when no stream processing is needed. • Because it's terminal, the stream cannot be reused after calling count() - a new stream must be created from the source for further processing. • Some stream sources let the JVM short-circuit count() without actually iterating all elements when no filtering is involved.

Example: Given the list [3, 7, 2, 9, 4], filtering for values greater than 5 and calling count() returns 2, since only 7 and 9 satisfy the condition.

Code Example:

long count = numbers.stream()
        .filter(n -> n > 5)
        .count();

Interview Tip: A concise interview answer is:

"count() is a terminal operation that returns how many elements are left in the stream, typically after filtering with a condition. I use numbers.stream().filter(n -> n > 5).count() to count elements matching a predicate rather than looping manually."