欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【如何判断集合中是否有符合条件的元素?】

程序员文章站 2022-06-10 18:36:32
...

工作中常有判断集合中是否存在符合条件的元素的需求,最原始的手段就是使用for循环挨个判断,但是自Java8开始我们有了其它更方便的选项。

public class User {

    private String name;

    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

   
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User("张三", 29));
        list.add(new User("李四", 21));
        list.add(new User("王五", 20));
        list.add(new User("马六", 22));

        User tom = new User("赵七", 23);

        // 方法一
//        if (!list.stream().filter(o -> o.getAge() == tom.getAge()).findFirst().isPresent()){
//            list.add(tom);
//        }

        // 方法二 noneMatch():根据判断条件,所有元素都不符合,则返回false
//        if (list.stream().noneMatch(o -> o.getAge() == tom.getAge())){
//            list.add(tom);
//        }

        // 方法三 allMatch():根据判断条件,所有元素都符合,则返回true
        if (list.stream().allMatch(o -> o.getAge() != tom.getAge())){
            list.add(tom);
        }

        System.out.println(list);
    }
}

// 运行结果
// [User{name='张三', age=29}, User{name='李四', age=21}, User{name='王五', age=20}, User{name='马六', age=22}, User{name='赵七', age=23}]