I need to delete some objects from an ArrayList
if they meet a condition and I\'m wondering which way could be more efficient.
Here\'s the situation: I
I have found an alternative faster solution:
int j = 0;
for (Iterator i = list.listIterator(); i.hasNext(); ) {
j++;
if (campo.getNome().equals(key)) {
i.remove();
i = list.listIterator(j);
}
}
Most performant would, I guess, be using the listIterator method and do a reverse iteration:
for (ListIterator<E> iter = list.listIterator(list.size()); iter.hasPrevious();){
if (weWantToDelete(iter.previous())) iter.remove();
}
Edit: Much later, one might also want to add the Java 8 way of removing elements from a list (or any collection!) using a lambda or method reference. An in-place filter for collections, if you like:
list.removeIf(e -> e.isBad() && e.shouldGoAway());
This is probably the best way to clean up a collection. Since it uses internal iteration, the collection implementation could take shortcuts to make it as fast as possible (for ArrayList
s, it could minimize the amount of copying needed).
With an iterator you can handle always the element which comes to order, not a specified index. So, you should not be troubled with the above matter.
Iterator itr = list.iterator();
String strElement = "";
while(itr.hasNext()){
strElement = (String)itr.next();
if(strElement.equals("2"))
{
itr.remove();
}
Maybe Iterator’s remove() method? The JDK’s default collection classes should all creator iterators that support this method.
Unless you're positive that the issue you're facing is indeed a bottleneck, I would go for the readable
public ArrayList filterThings() {
ArrayList pileOfThings;
ArrayList filteredPileOfThings = new ArrayList();
for (Thing thingy : pileOfThings) {
if (thingy.property != 1) {
filteredPileOfThings.add(thingy);
}
}
return filteredPileOfThings;
}
First, I'd make sure that this really is a performance bottleneck, otherwise I'd go with the solution that is cleanest and most expressive.
If it IS a performance bottleneck, just try the different strategies and see what's the quickest. My bet is on creating a new ArrayList and puting the desired objects in that one, discarding the old ArrayList.