Home >Java >javaTutorial >How does java Count count elements in a stream?
Explanation
1. Count is a terminal operation that can count the total number of elements in the stream. The return value is of long type.
2. count() returns the count of elements in the stream. This is a special case of induction (an induction operation takes a sequence of input elements and combines them into a summary result by repeatedly applying the combining operation). This is a terminal operation and may have consequences and side effects. After a terminal operation is performed, the pipe is considered consumed and cannot be reused.
Example
// 验证 list 中 string 是否有以 a 开头的, 匹配到第一个,即返回 true boolean anyStartsWithA = stringCollection .stream() .anyMatch((s) -> s.startsWith("a")); System.out.println(anyStartsWithA); // true // 验证 list 中 string 是否都是以 a 开头的 boolean allStartsWithA = stringCollection .stream() .allMatch((s) -> s.startsWith("a")); System.out.println(allStartsWithA); // false // 验证 list 中 string 是否都不是以 z 开头的, boolean noneStartsWithZ = stringCollection .stream() .noneMatch((s) -> s.startsWith("z")); System.out.println(noneStartsWithZ); // true
The above is the detailed content of How does java Count count elements in a stream?. For more information, please follow other related articles on the PHP Chinese website!