Stream.count()
Counts the elements of a stream.
Available since: Java 8
Syntax
long count()Return value
longThe number of elements in the stream.
Examples
How many words are longer than three letters:
void main() {
long n = Stream.of("a", "tree", "is", "green", "and", "tall")
.filter(w -> w.length() > 3)
.count();
IO.println(n);
}Output:
3Notes
It returns a long, not an int. If you only need the size of a whole collection, list.size() is simpler — no stream required.
See also
- Collectors.counting() — A counting collector, usually used inside `groupingBy()`.
- Stream.filter() — Keeps only the stream elements that match a condition.
- List.size() — Returns the number of elements in a list.
In the tutorial
- What a stream is — The Java Stream API — the source, intermediate and terminal operations, creating streams, lazy evaluation and why a stream can be used only once.