Stream 查找与约束匹配

Stream 查找与约束匹配

函数

anyMatch(lambda表达式) 有任意满足lambda表达式的元素则返回true,否则返回false
allMatch(lambda表达式) 若所有表达式都满足lambda表达式则返回true,否则返回false
findFirst() 返回满足filter条件的第一个元素,存在则返回,否则抛异常
findAny() 返回满足filter条件的任意一个元素,存在则返回,否则抛异常
isPresent() 存在则返回true,否则返回false
ifPresent(lambda表达式) 存在则执行lambda表达式,否则不执行

实践

 @Test
    public void test8() {
        Employee e1 = new Employee(1, 21, "zhangsan", "F");
        Employee e2 = new Employee(2, 45, "lisi", "M");
        Employee e3 = new Employee(3, 60, "wangwu", "M");
        Employee e4 = new Employee(4, 32, "zhouliu", "F");
        Employee e5 = new Employee(5, 28, "zhaoqi", "M");
        Employee e6 = new Employee(6, 43, "qianba", "F");

        List<Employee> list = Arrays.asList(e1, e2, e3, e4, e5, e6);
        boolean b = list.stream().anyMatch(e -> e.getAge() > 58);
        System.out.println(b);
        boolean b1 = list.stream().allMatch(e -> e.getAge() > 58);
        System.out.println(b1);

        Optional<Employee> first = list.stream().filter(e -> e.getAge() > 40).findFirst();
        System.out.println(first.get());

        // 抛异常
//        Optional<Employee> first1 = list.stream().filter(e -> e.getAge() > 80).findFirst();
//        System.out.println(first1.get());

        Optional<Employee> any = list.stream().filter(e -> e.getAge() > 40).findAny();
        System.out.println(any.get());

        boolean present = list.stream().filter(e -> e.getAge() > 40).findFirst().isPresent();
        System.out.println(present);

        list.stream().filter(e -> e.getAge() > 40).findFirst().ifPresent(System.out::println);
    }

posted @ 2022-06-19 21:35  Oh,mydream!  阅读(153)  评论(0编辑  收藏  举报