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

  • 48
    点赞
  • 162
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Java 8 中的 Stream 接口提供了许多方法,其中包括 `match` 方法。`match` 方法用于检查流中的元素是否满足指定的条件。`match` 方法有三个变体:`allMatch`、`anyMatch` 和 `noneMatch`。它们分别表示:全部匹配、任意匹配和没有匹配。 下面是 `match` 方法的用法示例: 假设有一个 `List` 对象 `list`,其中包含整数元素。我们可以使用 `stream` 方法将其转换为一个流,并使用 `match` 方法检查流中的元素是否满足指定条件。 ```java List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 检查是否所有元素都大于 0 boolean allMatch = list.stream().allMatch(i -> i > 0); System.out.println(allMatch); // true // 检查是否存在元素大于 5 boolean anyMatch = list.stream().anyMatch(i -> i > 5); System.out.println(anyMatch); // true // 检查是否不存在元素小于 0 boolean noneMatch = list.stream().noneMatch(i -> i < 0); System.out.println(noneMatch); // true ``` 在以上示例中,首先将 `list` 对象转换为一个流,然后使用 `allMatch` 方法检查流中的所有元素是否都大于 0,如果都大于 0,则返回 `true`。接着使用 `anyMatch` 方法检查流中是否存在元素大于 5,如果存在,则返回 `true`。最后使用 `noneMatch` 方法检查流中是否不存在元素小于 0,如果不存在,则返回 `true`。 需要注意的是,在使用 `match` 方法时,流必须是有序的,否则结果可能是错误的。如果流是无序的,可以使用 `sorted` 方法对其进行排序,然后再使用 `match` 方法。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值