for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
String a = iter.next();
if (...) {
iter.remove();
}
}
Making an additional assumption that the list is of strings.
As already answered, an list.iterator() is needed. The listIterator can do a bit of navigation too.
–---------
Update
As @AyushiJain commented, there is
list.removeIf(...);
Answer from Joop Eggen on Stack OverflowQuestion and solution: How to delete or add an object to/from array list while iterating it.
Java how to remove element from List efficiently - Stack Overflow
(Java) Can't remove element from List/ArrayList, always gives NullPointerException or ConcurrentModificationException.
Nested iteration over same list, want to modify (remove) elements in the inner loop. Best practices?
Videos
for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
String a = iter.next();
if (...) {
iter.remove();
}
}
Making an additional assumption that the list is of strings.
As already answered, an list.iterator() is needed. The listIterator can do a bit of navigation too.
–---------
Update
As @AyushiJain commented, there is
list.removeIf(...);
You need to use Iterator and call remove() on iterator instead of using for loop.
Hi few days ago i was encountered a problem. While iterating an array list by a for each loop, i was trying to remove the current object in spesific conditional. Like:
Arraylist<someclass> mylist;
...
for (someclass element: mylist)
if element.data!=0; mylist.remove(element)
when i run the code it throws ConcurrentModificationException .
I think it is because of the size of arraylist changes and the next iteration also changes and it throws out error.
Then I remembered the solition from a book.
By iterating with a classic for loop from backwards, adding or removing an object to/from the end of the list wont effect the loop. So it should be:
for (int i=mylist.size()-1;i>=0;i--)
someclass element=mylist.get(i);
if element.data!=0; mylist.remove(i)
with this method it works and there was no error.
I was talking with u/AgardenerCoding about the problem. And he encouraged me to post this as it may be very useful for someone else searching for an answer to same problem.
Use an Iterator instead and use Iterator#remove method:
for (Iterator<String> it = a.iterator(); it.hasNext(); ) {
String str = it.next();
if (!str.equals("foo") || !str.equals("bar")) {
it.remove();
}
}
From your question:
messing with for iterators is not really good practice
In fact, if you code oriented to interfaces and use List instead of ArrayList directly, using get method could become into navigating through all the collection to get the desired element (for example, if you have a List backed by a single linked list). So, the best practice here would be using iterators instead of using get.
what is the best practice to remove items from a list efficiently?
Not only for Lists, but for any Collection that supports Iterable, and assuming you don't have an index or some sort of key (like in a Map) to directly access to an element, the best way to remove an element would be using Iterator#remove.
You have three main choices:
Use an
Iterator, since it has that handyremovemethod on it. :-)Iterator<String> it = list.iterator(); while (it.hasNext()) { if (/*...you want to remove `it.next()`...*/) { it.remove(); } }Loop backward through the list, so that if you remove something, it doesn't matter for the next iteration. This also has the advantage of only calling
list.size()once.for (int index = list.size() - 1; index >= 0; --index) { // ...check and optionally remove here... }Use a
whileloop instead, and only increment the index variable if you don't remove the item.int index = 0; while (index < list.size()) { if (/*...you want to remove the item...*/) { list.removeAt(index); } else { // Not removing, move to the next ++index; } }
Remember that unless you know you're dealing with an ArrayList, the cost of List#get(int) may be high (it may be a traversal). But if you know you're dealing with ArrayList (or similar), then...