removeIf()方法。从列表中删除所有元素。

3

我有一个用户列表,我想从列表中删除ID小于3的用户。

实际上,我是这样做的:

[...]
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);
[...]

我认为我没有使用正确的方法?


你是如何创建这个列表的?请分享代码行。 - azro
3个回答

9

使用单个removeIf方法:

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

编辑:

根据您所发布的错误信息,您试图从不可变集合中删除元素,这是不可能的。

您可以创建原始 List 的副本并从副本中删除元素:

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

我遇到了这个错误:2019-01-07 11:54:09.931 ERROR 171920 --- [ XNIO-4 task-3] o.z.problem.spring.common.AdviceTrait: Not Implemented java.lang.UnsupportedOperationException: null at java.util.Collections$UnmodifiableCollection.removeIf(Collections.java:1084) - Mercer
@Mercer 你正试图从一个不可修改的集合中移除元素,这就是为什么它失败的原因。 - Eran
或者从不可修改的集合中创建一个流,并使用 filterlist.stream().filter(p -> p.getPid() >= 3).collect(toList()); - Ousmane D.

1
您只能调用该方法一次:
  • without intermediate variable

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

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

0

以下是使用Project Reactor可以做的事情:

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

或者您可以使用标准库中已经存在的内容:list.stream().filter(p -> p.getPid() >= 3).collect(toList()); - Ousmane D.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接