其他分享
首页 > 其他分享> > Predicate基本用法

Predicate基本用法

作者:互联网

    @Data
    class Person {
        private String name;
        private Integer age;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Person person = (Person) o;
            return name.equals(person.name) && age.equals(person.age);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, age);
        }

        public Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }
    }
    @RequestMapping(value = "test6")
    public void test6(HttpServletResponse rsp) {

        //普通业务集合
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("小D", 26));
        personList.add(new Person("佳欣", 24));
        personList.add(new Person("铭康", 28));
        personList.add(new Person("小鹏", 25));
        personList.add(new Person("宇轩", 22));
        personList.add(new Person("小明", 27));

        //条件
        Predicate<Person> predicate = person -> person.getAge() > 22 && StrUtil.contains(person.getName(), "小");

        //以下条件等价于上面条件
        Predicate<Person> predicate1 = person -> person.getAge() > 22;
        Predicate<Person> predicate2 = person -> StrUtil.contains(person.getName(), "小");


        Map<Integer, Person> result = new HashMap<>();
        for (int i = 0; i < personList.size(); i++) {
            Person person = personList.get(i);
            if (predicate.test(person)) {
                result.put(i, person);
            }
            //以下不同写法,对于条件特别多用下面这种
//            if (predicate1.and(predicate2).test(person)) {
//                result.put(i, person);
//            }

        }
        System.out.println(result);
        return;
    }

结果

{0=TestController.Person(name=小D, age=26), 3=TestController.Person(name=小鹏, age=25), 5=TestController.Person(name=小明, age=27)}

标签:基本,Predicate,name,Person,age,用法,person,new,personList
来源: https://blog.csdn.net/qq_37749537/article/details/121457149