In Java 8:
objects.removeIf(o -> o.getAttribute() == null);
In prior versions:
for (Iterator<MyObject> it = objects.iterator(); it.hasNext();) {
if (it.next().getAttribute() == null)
it.remove();
}
Also see Removing items from a collection in java while iterating over it. (The for
loop as you've shown can throw ConcurrentModificationException
.)
Both of these are more efficient because they allow the collection to do the iteration and removal in the way that they want to, but I don't think it's particularly important here unless you have a giant collection and do this a lot.
As an example of how these could be better, the code the question shows has poor time complexity for a linked list (something like O(n2/2)
for a worst case, I think) because the call to objects.remove
requires another traversal. Using an Iterator
lets the list do the removal without traversing.
Using an Iterator
is still poor for an ArrayList
, though, because the elements get shifted every time. The Java 8 version is the best. ArrayList
uses a BitSet
and does the shifting all at once.