removeIf() method. removes all the elements from the List

Viewed 2257

I have a list of user, i want to delete from my list the user with an id < 3

Actually i do this:

[...]
int pid1 = 1;
int pid2 = 2;
int pid3 = 3;
Predicate<Person> personPredicate1 = p-> p.getPid() == pid1;
Predicate<Person> personPredicate2 = p-> p.getPid() == pid2;
Predicate<Person> personPredicate3 = p-> p.getPid() == pid3;
list.removeIf(personPredicate1);
list.removeIf(personPredicate2);
list.removeIf(personPredicate3);
[...]

I think I do not use the right method?

3 Answers

Use a single removeIf:

list.removeIf(p -> p.getPid() < 3);

EDIT:

Based on the error you posted, you are trying to remove elements from an immutable collection, which is not possible.

You can create a copy of the original List and remove elements from the copy:

List<Person> copy = new ArrayList<>(list);
copy.removeIf(p -> p.getPid() < 3);

You may call the method only once:

  • without intermediate variable

    list.removeIf(p -> p.getPid() < 3);
    
  • with intermediate variable

    Predicate<Person> predicate = p-> p.getPid() < 3;
    list.removeIf(predicate);
    

Here's something you can do using Project Reactor:

Flux.from(list).filter(a -> a.getId() > 3).collectList();  //retuns Mono<List<User>>
Related