Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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:

3

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.