java 根据给定条件从 ArrayList 中删除对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13316629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove objects from an ArrayList based on a given criteria
提问by user1724416
I would like to remove an element from an ArrayList
in Java if it meets a certain criteria.
如果某个元素ArrayList
满足特定条件,我想从Java 中删除它。
ie:
IE:
for (Pulse p : pulseArray) {
if (p.getCurrent() == null) {
pulseArray.remove(p);
}
}
I can understand why this does not work, but what is a good way to do this?
我可以理解为什么这不起作用,但是这样做的好方法是什么?
回答by Denys Séguret
You must use an Iterator
to iterate and the remove
function of the iterator (not of the list) :
您必须使用 anIterator
进行迭代和remove
迭代器的功能(不是列表):
Iterator<Pulse> iter = pulseArray.iterator();
while (iter.hasNext()) {
Pulse p = iter.next();
if (p.getCurrent()==null) iter.remove();
}
Note that the Iterator#removefunction is said to be optionnal but it isimplemented by the ArrayList's iterator.
请注意,Iterator#remove函数据说是可选的,但它是由 ArrayList 的迭代器实现的。
Here's the code of this concrete function from ArrayList.java :
这是 ArrayList.java 中这个具体函数的代码:
765 public void remove() {
766 if (lastRet < 0)
767 throw new IllegalStateException();
768 checkForComodification();
769
770 try {
771 ArrayList.this.remove(lastRet);
772 cursor = lastRet;
773 lastRet = -1;
774 expectedModCount = modCount;
775 } catch (IndexOutOfBoundsException ex) {
776 throw new ConcurrentModificationException();
777 }
778 }
779
780 final void checkForComodification() {
781 if (modCount != expectedModCount)
782 throw new ConcurrentModificationException();
783 }
784 }
The expectedModCount = modCount;
line is why it won't throw an exception when you use it while iterating.
该expectedModCount = modCount;
行就是为什么在迭代时使用它时它不会抛出异常的原因。
回答by Markus Schulte
You can use Collection::removeIf(Predicate filter)(available from Java8 onwards), here is a simple example:
您可以使用Collection::removeIf(Predicate filter)(从 Java8 开始可用),这是一个简单的例子:
final Collection<Integer> list = new ArrayList<>(Arrays.asList(1, 2));
list.removeIf(value -> value < 2);
System.out.println(list); // outputs "[2]"
回答by Rajarshee Mitra
No need to use iterator. With Java 8(streaming and filtering capability and lambdas) you can accomplish it using one line. For eg. the required code that does the operation you specified will be :
无需使用迭代器。使用Java 8(流和过滤功能以及 lambdas),您可以使用一行代码来完成它。例如。执行您指定的操作所需的代码将是:
pulseArray = pulseArray.stream().filter(pulse -> pulse != null).collect(Collectors.toList());
回答by dbyrne
As an alterative to using an iterator, you can use the Guavacollections library. This has the advantage of being more functional(if you are into that sort of thing):
作为使用迭代器的替代方法,您可以使用Guava集合库。这具有更实用的优点(如果你喜欢那种东西):
Predicate<Pulse> hasCurrent = new Predicate<Pulse>() {
@Override public boolean apply(Pulse input) {
return (input.getCurrent() != null);
}
};
pulseArray = Lists.newArrayList(Collections2.filter(pulseArray, hasCurrent));
回答by Yogendra Singh
When you are removing the elementfrom the same list, the index gets disturbed. Try little differently as below:
当您从同一列表中删除元素时,索引会受到干扰。尝试一点不同,如下所示:
for (int i=0; i < pulseArray.size(); i++) {
Pulse p = (Pulse)pulseArray.get(i);
if (p.getCurrent() == null) {
pulseArray.remove(p);
i--;//decrease the counter by one
}
}
回答by Simon Nickerson
You can't alter a collection that you're iterating through using methods on the collection. However, some iterators (including iterators on ArrayList
s) support a remove()
method that allows you to remove methods in the order that you're iterating.
您不能使用集合上的方法更改正在迭代的集合。但是,某些迭代器(包括ArrayList
s上的迭代器)支持一种remove()
方法,该方法允许您按照迭代的顺序删除方法。
Iterator<Pulse> iterator = pulseArray.iterator();
while (iterator.hasNext()) {
Pulse p = iterator.next();
if (p.getCurrent() == null) {
iterator.remove();
}
}
回答by Kakarot
Using an Iterator would give you the power of modifying the list while iterating through the arraylist
使用 Iterator 可以让您在遍历 arraylist 时修改列表