How to Remove Objects or Elements while Iterating over ArrayList in Java - The Right way

One of the common problems many Java Programmers face is to remove elements while iterating over ArrayList in Java because the intuitive solution doesn't work e.g. you just cannot go through an ArrayList using a for loop and remove an element depending upon some condition. Even though java.util.ArrayList provides remove() methods e.g. remove (int index) and remove (Object element), you cannot use them to remove elements while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration. The right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method.

When you use iterator's remove() method, ConcurrentModfiicationException is not thrown. because it also updates the counters and variables used by Iterator like modCount which indicate that modification is done by the Iterator itself and not somewhere around.

In this article, I'll show you an example of both ways and how they work in Java. You'll also learn a little bit about java.util.ConcurrentModificationException, which is a common problem for non-concurrent collection classes like ArrayList or HashMap.

Though, if you are completely new to Java and coming from a non-programming background, I suggest you to first go through a comprehensive Java course like The Complete Java MasterClass instead of learning from arbitrary articles.

The course provides structured learning which is both efficient and works great for beginners. Once you know the fundamentals, you can learn any topic by reading a blog post or individual tutorial, they will make more sense by then also




1. ArrayList remove() method Example

Now, let's see an example of removing elements from ArrayList while looping using for() loop and ArrayList.remove() method which is wrong and the program will throw ConcurrentModificationExcetpion upon execution.

import java.util.ArrayList;
import java.util.List;

/*
 * Java Program to remove an element while iterating over ArrayList
 */

public class Main {

  public static void main(String[] args) throws Exception {

    List<String> loans = new ArrayList<>();
    loans.add("personal loan");
    loans.add("home loan");
    loans.add("auto loan");
    loans.add("credit line loan");
    loans.add("mortgage loan");
    loans.add("gold loan");

    // printing ArrayList before removing any element
    System.out.println(loans);

    // removing element using ArrayList's remove method during iteration
    // This will throw ConcurrentModification

    for (String loan : loans) {
      if (loan.equals("personal loan")) {
        loans.remove(loan);
      }
    }

    // printing ArrayList after removing an element
    System.out.println(loans);
  }

}

Output
Exception in thread "main" [personal loan, home loan, auto loan, credit line loan, mortgage loan, gold loan]
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Main.main(Main.java:26)


Some of you may wonder that we are getting ConcurrentModificationException because we are not using the Iterator, but that's not true, even if you use Iterator you will get java.util.ConcurrentModificationException as long as you will use ArrayList's remove() method for removing element while iterationg as shown in following example:

Iterator<String> itr = loans.iterator();
    while (itr.hasNext()) {
      String loan = itr.next();
      if (loan.equals("personal loan")) {
        loans.remove(loan);
      }
    }


Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Main.main(Main.java:29)


In order to fix above code, you just need to remove the loans.remove(loan) with itr.remove() method, which is explained in the next example. Though, if you want to know more about Iterator and in general Java Collection Framework, which can feel daunting sometimes, I suggest you go through Java Fundamentals: Collections course on Pluralsight.

How to Remove Objects or Elements while Iterating over ArrayList in Java - The Right way

It's a perfect course to both learn and master the Java Collection framework.  Btw, you would need a Pluralsight membership to get access this course, which cost around $29 per month or $299 annually, but fortunately, they are offering 33% discount now, which means you can get the Pluralsight annual membership is just $199 (33% discount)  and save $100.

If you don't have Pluralsight membership, I encourage you to get one because it allows you to access their 5000+ online courses on all latest topics like front-end and back-end development, machine learning etc.  It also includes interactive quizzes, exercises, and latest certification material and you can also gift this course to your programmer friend.

It's like Netflix for Software Developers and Since learning is an important part of our job, Plurlasight membership is a great way to stay ahead of your competition.

They also provide a 10-day free trial without any commitment, which is a great way to not just access this course for free but also to check the quality of courses before joining Pluralsight.



2. Iterator's remove() method Example

Now, let's try the other approach which uses Iterator's remove() method to remove an element from ArrayList while iterating over it.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
 * Java Program to remove an element while iterating over ArrayList
 */

public class Main {

  public static void main(String[] args) throws Exception {

    List<String> loans = new ArrayList<>();
    loans.add("personal loan");
    loans.add("home loan");
    loans.add("auto loan");
    loans.add("credit line loan");
    loans.add("mortgage loan");
    loans.add("gold loan");

    // printing ArrayList before removing any element
    System.out.println(loans);

    // removing element using ArrayList's remove method during iteration
    // This will throw ConcurrentModification

    Iterator<String> itr = loans.iterator();
    while (itr.hasNext()) {
      String loan = itr.next();
      if (loan.equals("personal loan")) {
        itr.remove();
      }
    }

    // printing ArrayList after removing an element
    System.out.println(loans);
  }

}

Output
[personal loan, home loan, auto loan, credit line loan, mortgage loan, gold loan]
[home loan, auto loan, credit line loan, mortgage loan, gold loan]

From the output, you can see that "personal loan" element is removed from the ArrayList. Size of the ArrayList is also reduced by one and there is no ConcurrentModficiationException in the code.


That's all about how to remove elements while iterating over ArrayList in Java. As I have said that if you use ArrayList's remove() method like remove(int index) or remove(Object obj) while iterating over ArrayList then a ConcurrentModfiicationException will be thrown. You can avoid that by using Iterator's remove() method, which removes the current object in the iteration.

Further Learning
The Complete Java Masterclass
Java Fundamentals: Collections
Data Structures and Algorithms: Deep Dive Using Java


Other ArrayList tutorials for Java Programmers
  • How to remove duplicate elements from ArrayList in Java? (tutorial)
  • How to create and initialize ArrayList in the same line? (example)
  • Difference between ArrayList and HashSet in Java? (answer)
  • Difference between an Array and ArrayList in Java? (answer)
  • How to reverse an ArrayList in Java? (example)
  • How to loop through an ArrayList in Java? (tutorial)
  • How to synchronize an ArrayList in Java? (read)
  • When to use ArrayList over LinkedList in Java? (answer)
  • Difference between ArrayList and HashMap in Java? (answer)
  • Difference between ArrayList and Vector in Java? (answer)
  • How to sort an ArrayList in descending order in Java? (read)
  • How to get sublist from ArrayList in Java? (example)
  • How to convert CSV String to ArrayList in Java? (tutorial)

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a note. If you like, you can also follow me on Twitter, my id is @javinpaul.


No comments:

Post a Comment