java8 .stream.anyMatch / allMatch / noneMatch用法

时间:2025-03-17 07:09:37

java8 stream接口终端操作 anyMatch,allMatch,noneMatch

anyMatch:判断的条件里,任意一个元素成功,返回true

allMatch:判断条件里的元素,所有的都是,返回true

noneMatch:与allMatch相反,判断条件里的元素,所有的都不是,返回true

count方法,跟List接口中的 .size() 一样,返回的都是这个集合流的元素的长度,不同的是,流是集合的一个高级工厂,中间操作是工厂里的每一道工序,我们对这个流操作完成后,可以进行元素的数量的和;

栗子:

public static void main(String[] args) {

    List<Integer> list = (1, 2, 1, 1, 1);
    
    boolean anyMatch = ().anyMatch(f -> f == (1));
    boolean allMatch = ().allMatch(f -> f == (1));
    boolean noneMatch = ().noneMatch(f -> f == (1));
    long count = ().filter(f -> f == (1)).count();
    
    (anyMatch);  // true
    (allMatch);  // false
    (noneMatch); // false
    (count);     // 4
}

如果想了解更详细,或者了解java8更多知识点,可参考以下博文:
参考博文:/qq_28410283/article/details/80783946