2

So I was wondering if there was a more efficient way to do this in java? Assuming the list of objects is currently populated...

for (Object obj : objects) {
   if (obj.getAttribute() == null) {
      objects.remove(obj);
   }
}

Essentially, I just want to be able to remove any objects from a given list if objects in that list contain a specific null attribute. Thoughts?

This 0ne Pr0grammer
  • 2,632
  • 14
  • 57
  • 81
  • 1
    You cannot remove objects the way you've written the code without the possibility of introducing a ConcurrentModificationException. – Amir Afghani May 06 '15 at 22:54

1 Answers1

4

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.

Community
  • 1
  • 1
Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • 1
    Ah, didn't even think about that exception being thrown. And unfortunately I'm working in an environment in which we don't currently use Java 8, so the latter option using the iterator is the one I must go with. But I'll keep that `removeIf` in the back of my mind in case we do decide to upgrade our java version here. Thank you for your help! – This 0ne Pr0grammer May 06 '15 at 23:49
  • 1
    Iterators are pretty ugly. : ) – Radiodef May 06 '15 at 23:53