In Java How to remove elements from ArrayList while iterating? The list.remove(s) will throws java.util.ConcurrentModificationException, if you remove an item from an ArrayList while iterating it.
Let’s get started.
Create class: CrunchifyRemoveItemFromList.java
We will use below 5 methods
to remove an element from ArrayList while iterating it.
- Method-1: collectionRemoveIf Method
- Method-2: collectionRemoveIfObjectEquals Method
- Method-3: collectionteratorRemove Method
- Method-4: listIteratorWayToRemoveElement Method
- Method-5: streamFilterCollectWay Method
Copy below code and save it.
package crunchify.com.java.tutorials; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.stream.Collectors; /** * @author Crunchify.com * In Java How to remove Elements while Iterating a List? (5 different ways to remove items) */ public class CrunchifyRemoveItemFromList { public static void main(String[] args) { collectionRemoveIfMethod(); collectionRemoveIfObjectEqualsMethod(); collectionteratorRemoveMethod(); listIteratorWayToRemoveElement(); streamFilterCollectWay(); } // Method-1: collectionRemoveIfMethod to remove elements from ArrayList private static void collectionRemoveIfMethod() { List<String> crunchifyList = new ArrayList<>(); crunchifyList.add("Google.com"); crunchifyList.add("Crunchify.com"); crunchifyList.add("Facebook.com"); crunchifyList.add("Apple.com"); // removeIf(): Removes all of the elements of this collection that satisfy the given predicate. // Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller. crunchifyList.removeIf("Apple.com"::equals); // equals(): Compares this string to the specified object. // The result is true if and only if the argument is not null and is a // String object that represents the same sequence of characters as this object. // For finer-grained String comparison, refer to java.text.Collator. System.out.print("Method-1 Result: "); crunchifyPrint(crunchifyList); } // Simple print function private static void crunchifyPrint(List<String> crunchifyList) { System.out.println(crunchifyList); } // Method-2: collectionRemoveIfObjectEqualsMethod to remove elements from ArrayList private static void collectionRemoveIfObjectEqualsMethod() { List<String> crunchifyList = new ArrayList<>(); crunchifyList.add("Google.com"); crunchifyList.add("Crunchify.com"); crunchifyList.add("Facebook.com"); crunchifyList.add("Apple.com"); // removeIf() Params: // filter – a predicate which returns true for elements to be removed // Returns: // true if any elements were removed // Throws: // NullPointerException – if the specified filter is null crunchifyList.removeIf(crunchify -> Objects.equals(crunchify, "Crunchify.com") || Objects.equals(crunchify, "Apple.com")); System.out.print("Method-2 Result: "); crunchifyPrint(crunchifyList); } // Method-3: collectionteratorRemoveMethod to remove elements from ArrayList private static void collectionteratorRemoveMethod() { List<String> crunchifyList = new ArrayList<>(); crunchifyList.add("Google.com"); crunchifyList.add("Crunchify.com"); crunchifyList.add("Facebook.com"); crunchifyList.add("Apple.com"); // listIterator(): Returns a list iterator over the elements in this list (in proper sequence). ListIterator<String> crunchifyIterator = crunchifyList.listIterator(); // hasNext(): Returns true if this list iterator has more elements when traversing the list in the forward direction. // (In other words, returns true if next would return an element rather than throwing an exception.) while (crunchifyIterator.hasNext()) { // equals(): Compares this string to the specified object. // The result is true if and only if the argument is not null and is a // String object that represents the same sequence of characters as this object. //For finer-grained String comparison, refer to java.text.Collator. if ("Crunchify.com".equals(crunchifyIterator.next())) { // next(): returns the next element in the list and advances the cursor position. // This method may be called repeatedly to iterate through the list, or intermixed with calls to previous to go back and forth. // (Note that alternating calls to next and previous will return the same element repeatedly.) crunchifyIterator.remove(); // remove(): Removes from the list the last element that was returned by next or previous (optional operation). // This call can only be made once per call to next or previous. It can be made only if add has not been called after the last call to next or previous. } } System.out.print("Method-3 Result: "); crunchifyPrint(crunchifyList); } // Method-4: listIteratorWayToRemoveElement to remove elements from ArrayList private static void listIteratorWayToRemoveElement() { List<String> crunchifyList = new ArrayList<>(); crunchifyList.add("Google.com"); crunchifyList.add("Crunchify.com"); crunchifyList.add("Facebook.com"); crunchifyList.add("Apple.com"); List<String> crunchifyNewList = new ArrayList<>(); for (String s : crunchifyList) { if (!"Facebook.com".equals(s)) { crunchifyNewList.add(s); } } System.out.print("Method-4 Result: "); crunchifyPrint(crunchifyNewList); } // Method-5: streamFilterCollectWay to remove elements from ArrayList private static void streamFilterCollectWay() { List<String> crunchifyList = new ArrayList<>(); crunchifyList.add("Google.com"); crunchifyList.add("Crunchify.com"); crunchifyList.add("Facebook.com"); crunchifyList.add("Apple.com"); // stream(): Returns a sequential Stream with this collection as its source. // This method should be overridden when the spliterator() method cannot return a spliterator // that is IMMUTABLE, CONCURRENT, or late-binding. (See spliterator() for details.) // filer(): Returns a stream consisting of the elements of this stream that match the given predicate. // This is an intermediate operation. List<String> crunchifyNewList = crunchifyList. stream(). filter(crunchify -> !"Crunchify.com". equals(crunchify)) .collect(Collectors.toList()); // toList(): Returns a Collector that accumulates the input elements into a new List. // There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; // if more control over the returned List is required, use toCollection(Supplier). System.out.print("Method-5 Result: "); crunchifyPrint(crunchifyNewList); } }
Just run above program as a Java Application and you will see result as below. You won’t see Concurrent Modification Exception.
Here is java.util.Collection.removeIf() method:
IntelliJ IDEA console result:
We moved to IntelliJ IDEA from Eclipse last year and we loved it. Here is a console result.
/Users/app/Library/Java/JavaVirtualMachines/openjdk-17.0.1/Contents/Home/bin/java --enable-preview -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar crunchify.com.java.tutorials.CrunchifyRemoveItemFromList Method-1 Result: [Google.com, Crunchify.com, Facebook.com] Method-2 Result: [Google.com, Facebook.com] Method-3 Result: [Google.com, Facebook.com, Apple.com] Method-4 Result: [Google.com, Crunchify.com, Apple.com] Method-5 Result: [Google.com, Facebook.com, Apple.com] Process finished with exit code 0
Let me know if you face any problem running this Java program.