Java 25 (LTS) reference · Stream API

Java Stream count() Method

Return the number of elements in the stream (a long). A terminal operation.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

stream.count()

Return value

A long.

Examples

Count matches
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        long evens = IntStream.rangeClosed(1, 10).filter(n -> n % 2 == 0).count();
        System.out.println(evens);
    }
}

Output

5

Run this on your computer — see “Get Started” for setup.

Count log errors
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<String> logs = List.of("INFO a", "ERROR b", "ERROR c");
        System.out.println(logs.stream().filter(l -> l.startsWith("ERROR")).count() + " errors");
    }
}

Output

2 errors

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?