During removing object from List or Set are facing java.util.ConcurrentModificationException following exception here is solution for it. I like to solve it using Java 8 streaming.

Bad Code:

List<String> names = new ArrayList<>(Arrays.asList("join","Morry","John","Jok","Sand"));
        for(String name:names){
            if(name.startsWith("J")){
                names.remove(name);
            }
        }

 

Exception in thread "main" java.util.ConcurrentModificationException
  at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:937)
  at java.base/java.util.ArrayList$Itr.next(ArrayList.java:891)
  at module.maven.demo/com.javadeveloperzone.CollectionRemoveElement.example2(CollectionRemoveElement.java:24)
  at module.maven.demo/com.javadeveloperzone.CollectionRemoveElement.main(CollectionRemoveElement.java:17)

Solution 1: Remove using removeIf method. (Only for Java 8)

List<String> names = new ArrayList<>(Arrays.asList("join", "Morry", "John", "Jok", "Sand"));
       System.out.println("Print All names");
       names.forEach(System.out::println);
       names.removeIf((name) -> {
           return name.startsWith("J");
       });
       System.out.println("Print after Remove names start with j");
       names.forEach((name) -> System.out.println(name));

Output:

Print All names
join
Morry
John
Jok
Sand
Print after Remove names start with j
join
Morry
Sand

 

Solution 2: Remove using iterator

List<String> names = new ArrayList<>(Arrays.asList("join", "Morry", "John", "Jok", "Sand"));
       System.out.println("Print All names");
       names.forEach(System.out::println);
       Iterator<String> stringIterator = names.iterator();
       while (stringIterator.hasNext()) {
           String name = stringIterator.next();
           if (name.startsWith("J")) {
               stringIterator.remove();
           }
       }
       System.out.println("Print after Remove names start with j");
       names.forEach((name) -> System.out.println(name));

 Output:

Print All names
join
Morry
John
Jok
Sand
Print after Remove names start with j
join
Morry
Sand

 

Was this post helpful?

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *