Removing an element from a Map in Java

Rafael Ferreira :

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 ?

YCF_L :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421730&siteId=1