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
Syntax
stream.count()
Return value
A long.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
stream.filter()· Keep only the elements that match a condition. Intermediate and lazy: nothing runs until a terminal operation.stream.anyMatch()· Return true if any element matches a condition, stopping at the first match. allMatch() and noneMatch() are similar.- Java Streams · tutorial