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 have a class that contains an ArrayList
containing some other objects. I have to iterate over this ArrayList
and delete all elements meeting a certain condition. As far as I know, those would be my options to delete:
Create a new ArrayList
and add the elements that doesn't meet the condition. After the iteration, swap from the old arraylist to the new one without the elements.
Create a new ArrayList
and add the elements that meet the condition. After the iteration, use the removeAll()
method passing the ArrayList
with the objects to be deleted.
Is there a more efficient way to delete objects from an ArrayList
?
Core Java bootcamp program with Hands on practice The List provides removeAll() method to remove all elements of a list that are part of the collection provided.
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.
You could iterate backwards and remove as you go through the ArrayList. This has the advantage of subsequent elements not needing to shift and is easier to program than moving forwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With