java8 .stream().anyMatch / allMatch / noneMatch用法

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

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

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

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

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

栗子:

public static void main(String[] args) {

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

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

猜你喜欢

转载自blog.csdn.net/weixin_44958006/article/details/108112064