简体   繁体   中英

Predicate behaviour with List.removeIf()

I have a person class with name and age member variable. I have 2 predicate methods as below.

    static Predicate<Person> isAbove20(){
        return p -> p.getAge() > 20;
    }

    static Predicate<Person> isNameEqualTo(String name){
        return p -> p.getName().equals(name);
    }

I have a list of Person and few lines of code as below.

    List<Person> people = new ArrayList<>();
    people.add(new Person("raj", 20));
    people.add(new Person("bini", 15));
    people.add(new Person("tom", 25));
    people.add(new Person("rock", 12));

    print(people);
    people.removeIf(Predicates.isNameEqualTo("rock").and(Predicates.isAbove20()));
    System.out.println("**** after applying predicates ****");
    print(people);

On running this code I get output as

Person{name='raj', age=20}
Person{name='bini', age=15}
Person{name='tom', age=25}
Person{name='rock', age=12}
**** after applying predicates ****
Person{name='raj', age=20}
Person{name='bini', age=15}
Person{name='tom', age=25}
Person{name='rock', age=12}

I was expecting it to remove 2 Person objects from the list .ie rock (for name being "rock") and tom (for age above 20)) print the list content as

Person{name='raj', age=20}
Person{name='bini', age=15}

Could someone please explain why it is printing the entire list as it was created.

Thanks.

You're confusing "and" with "or". Your predicate removes a person if the name is rock and the age is > 20.

No person matches this predicate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM