Home > Java > javaTutorial > body text

How does java Count count elements in a stream?

WBOY
Release: 2023-05-11 16:07:06
forward
1562 people have browsed it

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
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template