[java] Deleting objects from an ArrayList in Java

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:

  1. 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.

  2. 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?

This question is related to java performance memory-management arraylist

The answer is


Obviously, of the two methods you mention number 1 is more efficient, since it only needs to go through the list once, while with method number 2 the list has to be traversed two times (first to find the elements to remove, and them to remove them).

Actually, removing a list of elements from another list is likely an algorithm that's worse than O(n) so method 2 is even worse.

The iterator method:

List data = ...;

for (Iterator i = data.iterator(); i.hasNext(); ) {
    Object element = i.next();

    if (!(...)) {
        i.remove();
    }
}

I'm good with Mnementh's recommentation.
Just one caveat though,

 ConcurrentModificationException

Mind that you don't have more than one thread running. This exception could appear if more than one thread executes, and the threads are not well synchronized.


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;
}

There is a hidden cost in removing elements from an ArrayList. Each time you delete an element, you need to move the elements to fill the "hole". On average, this will take N / 2 assignments for a list with N elements.

So removing M elements from an N element ArrayList is O(M * N) on average. An O(N) solution involves creating a new list. For example.

List data = ...;
List newData = new ArrayList(data.size()); 

for (Iterator i = data.iterator(); i.hasNext(); ) {
    Object element = i.next();

    if ((...)) {
        newData.add(element);
    }
}

If N is large, my guess is that this approach will be faster than the remove approach for values of M as small as 3 or 4.

But it is important to create newList large enough to hold all elements in list to avoid copying the backing array when it is expanded.


int sizepuede= listaoptionVO.size();
for (int i = 0; i < sizepuede; i++) {
    if(listaoptionVO.get(i).getDescripcionRuc()==null){
        listaoptionVO.remove(listaoptionVO.get(i));
        i--;
        sizepuede--;
     }
}

edit: added indentation


Whilst this is counter intuitive this is the way that i sped up this operation by a huge amount.

Exactly what i was doing:

ArrayList < HashMap < String , String >> results; // This has been filled with a whole bunch of results

ArrayList < HashMap < String , String > > discard = findResultsToDiscard(results);

results.removeall(discard);

However the remove all method was taking upwards of 6 seconds (NOT including the method to get the discard results) to remove approximately 800 results from an array of 2000 (ish).

I tried the iterator method suggested by gustafc and others on this post.

This did speed up the operation slightly (down to about 4 seconds) however this was still not good enough. So i tried something risky...

 ArrayList < HashMap < String, String>> results;

  List < Integer > noIndex = getTheDiscardedIndexs(results);

for (int j = noIndex.size()-1; j >= 0; j-- ){
    results.remove(noIndex.get(j).intValue());
}

whilst the getTheDiscardedIndexs save an array of index's rather then an array of HashMaps. This it turns out sped up removing objects much quicker ( about 0.1 of a second now) and will be more memory efficient as we dont need to create a large array of results to remove.

Hope this helps someone.


Maybe Iterator’s remove() method? The JDK’s default collection classes should all creator iterators that support this method.


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();
  }

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.


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 ArrayLists, it could minimize the amount of copying needed).


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);
    }
  }

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to memory-management

When to create variables (memory management) How to check if pytorch is using the GPU? How to delete multiple pandas (python) dataframes from memory to save RAM? Is there a way to delete created variables, functions, etc from the memory of the interpreter? C++ error : terminate called after throwing an instance of 'std::bad_alloc' How to delete object? Android Studio - How to increase Allocated Heap Size Implementing IDisposable correctly Calculating Page Table Size Pointer-to-pointer dynamic two-dimensional array

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable