从列表中删除符合指定条件的对象 [英] Remove object from list that matched a specified criteria
问题描述
我的List
为Pojo
,其中有大约10000个对象.
I have a List
of Pojo
which has about 10000 objects.
我需要从pojo.getAccountId() = provided String
所在的List
中删除一个对象.
I need to remove an object from this List
where pojo.getAccountId() = provided String
.
是否可以删除该对象而不必遍历整个列表? 我必须进行大量删除操作,所以我不想遍历列表.
Is this possible to remove this object without having to iterate over the whole list? I have to do a lot of removals and so I don't want to iterate over the list.
当前,我打算从列表中的key = pojo.getAccountId()
创建一个hashmap<>
.使用地图我可以做map.remove(key)
.
Currently I am planning to create a hashmap<>
from my list where key = pojo.getAccountId()
. Using map i can do map.remove(key)
.
如果可能的话,我想完全避免这种转换过程.
I would like to avoid this conversion process if possible at all.
推荐答案
我喜欢使用apache commons库中的CollectionUtils.它有一个过滤器方法,您需要将谓词传递给该方法.
I like to use the CollectionUtils from the apache commons library. It has a filter method to which you need to pass a predicate.
public void filterList(List<MyObject> myList, String testString) {
CollectionUtils.filter(myList, new Predicate<MyObject>() {
@Override
public boolean evaluate(MyObject myObject) {
return myObject.getAccountId().equals(testString);
}
});
}
这将从列表中删除所有不符合条件的对象.如果要执行相反的操作,则可以更改条件,也可以使用 filterInverse 方法. 不过,当然,它隐式地使用了for循环,但对您而言是隐藏的.
This removes from the list all the objects that do not match the condition described in the Predicate. If you want to do the opposite, you can change the condition, or you can use the filterInverse method. Nevertheless, of course, it implicitly uses a for loop, but it is hidden to you.
Apache Commons: http://commons.apache.org/proper/commons-collections/
Apache commons : http://commons.apache.org/proper/commons-collections/
CollectionUtils: http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html
CollectionUtils : http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html
希望这很有帮助.
编辑
正如Narmer所说,如果您使用JDK 1.8,它甚至更容易.您可以在列表上创建流,并以相同的方式调用filter方法.
As also said by Narmer, if you use JDK 1.8, it is even easier. You can create a stream on your list and call the filter Method in the same way.
myList.stream()
.filter(myObject -> myObject.getAccountId().equals(testString))
.collect(Collectors.toList())
这篇关于从列表中删除符合指定条件的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!