1

I am trying to remove an element from my map and it is giving an error.

CODE:

Map<String, String> map = ["a":"test",
           "b":"test",
           "c":"test",
           "d":""]

for (data in map.entrySet()){
    if (data.getValue() != ""){
        map.remove(data.getKey())
    }
}

ERROR:

Caught: java.util.ConcurrentModificationException*
java.util.ConcurrentModificationException
at first_script.run(first_script.groovy:6)

Process finished with exit code 1

I know it´s happening because I am trying to remove it at the same time. is there any way of doing it without creating a list for the elements I need to remove ?

Rafael Ferreira
  • 329
  • 2
  • 16
  • 2
    It's happening because you are removing something from the map while you are looping through it at the same time – rhowell Feb 11 '20 at 16:11
  • 1
    Duplicate of [iterating over and removing from a map](https://stackoverflow.com/questions/1884889/iterating-over-and-removing-from-a-map) – Govinda Sakhare Feb 11 '20 at 16:14

1 Answers1

2

try to use removeIf, note also that you have to use equals to check strings :

map.entrySet().removeIf(e -> !e.getValue().equals(""));

or better in your case, you can use isEmpty :

map.entrySet().removeIf(e -> !e.getValue().isEmpty())

Or mach better and because you based on the values in your condition, you can use values(), instead of entrySet():

map.values().removeIf(v -> !v.isEmpty());
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140