Java 8 Stream: allMatch, anyMatch和noneMatch示例
Java 8 Stream
allMatch
, anyMatch
和noneMatch
方法应用于与给定Predicate
匹配的流对象,然后返回布尔值。
allMatch()
检查调用流是否与给定Predicate
完全匹配,如果是,则返回true
,否则返回false
。
anyMatch()
检查流中是否有与给定Predicate
匹配的元素,如果是,则返回true
,否则返回false
。
noneMatch()
仅当没有元素与给定Predicate
匹配才返回true
。
Stream.allMatch
我们将Predicate
作为参数传递给allMatch()
方法。
该Predicate
应用于流的每个元素,如果每个元素都满足给定的Predicate
,则返回true
,否则返回false
。
Stream.anyMatch
对于anyMatch()
方法,我们将Predicate
作为参数传递。
流的元素为此Predicate
进行迭代。如果有元素匹配,则返回true
,否则返回false
。
Stream.noneMatch
对于noneMatch()
方法,我们将Predicate
作为参数传递。
如果流中的任何元素都不匹配给定的Predicate
,则返回true
,否则返回false
。
代码示例
MatchDemo.java
import java.util.List;
import java.util.function.Predicate;
public class MatchDemo {
public static void main(String[] args) {
Predicate<Employee> p1 = e -> e.id < 10 && e.name.startsWith("A");
Predicate<Employee> p2 = e -> e.sal < 10000;
List<Employee> list = Employee.getEmpList();
//using allMatch
boolean b1 = list.stream().allMatch(p1);
System.out.println(b1);
boolean b2 = list.stream().allMatch(p2);
System.out.println(b2);
//using anyMatch
boolean b3 = list.stream().anyMatch(p1);
System.out.println(b3);
boolean b4 = list.stream().anyMatch(p2);
System.out.println(b4);
//using noneMatch
boolean b5 = list.stream().noneMatch(p1);
System.out.println(b5);
}
}
Employee.java
import java.util.ArrayList;
import java.util.List;
public class Employee {
public int id;
public String name;
public int sal;
public Employee(int id,String name,int sal ){
this.id = id;
this.name = name;
this.sal = sal;
}
public static List<Employee> getEmpList(){
List<Employee> list = new ArrayList<>();
list.add(new Employee(1, "A", 2000));
list.add(new Employee(2, "B", 3000));
list.add(new Employee(3, "C", 4000));
list.add(new Employee(4, "D", 5000));
return list;
}
}
输出
false
true
true
true
false