开发手册 欢迎您!
软件开发者资料库

Java Stream allMatch、noneMatch 和 anyMatch 的使用

Stream是Java 8的新特性,基于lambda表达式,是对集合对象功能的增强,它专注于对集合对象进行各种高效、方便聚合操作或者大批量的数据操作,提高了编程效率和代码可读性。本文主要介绍Java Stream中 allMatch、noneMatch和anyMatch的使用,以及相关的示例代码。

1、使用anyMatch条件判断

判断数据集合中是否存在任意一个元素符合设置的predicate条件( [boolean] anyMatch(Predicate predicate);),如存在就返回true,否则返回false

例如,

import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {   public static class Person {     int age;     Person (int age) {         this.age = age;     }     public int getAge() {         return age;     }     public void setAge(int age) {         this.age = age;     }  }public static void main(String[] args) {    List pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));    pList.stream().forEach(o->{       System.out.println("stream() map() before :"+o.getAge());    });    //任意一个元素满足条件(年龄大于30),返回true。    boolean result = pList.stream().anyMatch(obj-> obj.getAge()>30);    System.out.println("stream() result :"+result);    System.exit(0); //success  }}

2、使用noneMatch条件判断

判断数据集合中全部元素都不符合设置的predicate条件( boolean noneMatch(Predicate predicate);),如全部不符合返回true,否则返回false

例如,

import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {   public static class Person {     int age;     Person (int age) {         this.age = age;     }     public int getAge() {         return age;     }     public void setAge(int age) {         this.age = age;     }  }public static void main(String[] args) {    List pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));    pList.stream().forEach(o->{       System.out.println("stream() map() before :"+o.getAge());    });    //全部元素不满足条件(年龄大于30),有满足的则返回false。    boolean result = pList.stream().noneMatch(obj-> obj.getAge()>30);    System.out.println("stream() result :"+result);    result = pList.stream().noneMatch(obj-> obj.getAge()<10);    System.out.println("stream() result :"+result);    System.exit(0); //success  }}

3、使用allMatch条件判断

判断数据集合中全部元素都符合元素设置的predicate条件( boolean allMatch(Predicate predicate);),如满足就返回true,否则返回false。如下,

import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {   public static class Person {     int age;     Person (int age) {         this.age = age;     }     public int getAge() {         return age;     }     public void setAge(int age) {         this.age = age;     }  }public static void main(String[] args) {    List pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));    pList.stream().forEach(o->{       System.out.println("stream() map() before :"+o.getAge());    });    //所有元素满足条件(年龄大于30),不满足就返回false。    boolean result = pList.stream().allMatch(obj-> obj.getAge()>30);    System.out.println("stream() result :"+result);    System.exit(0); //success  }}