Stream

88 阅读1分钟

匹配和查询

boolean anyMatch(Predicate<? super T> predicate)

只要有一个条件满足即返回true

boolean allMatch(Predicate<? super T> predicate)

必须全部都满足才会返回true

boolean noneMatch(Predicate<? super T> predicate)

全都不满足才会返回true

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);	//false
     boolean b2 = list.stream().allMatch(p2);
     System.out.println(b2);	//true
     //using anyMatch
     boolean b3 = list.stream().anyMatch(p1);
     System.out.println(b3);	//true
     boolean b4 = list.stream().anyMatch(p2);
     System.out.println(b4);	//true
     //using noneMatch
     boolean b5 = list.stream().noneMatch(p1);
     System.out.println(b5);	//false
     
  }    
} 


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;
    }
} 

参考文档:

moonce.blog.csdn.net/category_10…

www.concretepage.com/java/java-8…