remove any key value that is equal to the string "world" in an instance of LinkedHashMap, using for-each loop and Map.Entry(), but always get error

Viewed 254

I tried to go over an instance of LinkedHashMap and remove any key value that is equal to the string "world", using for-each loop and Map.Entry(). However, the IDE always output an error message. Could someone give me a hint as to why is this happening? Thanks in advance for any help!

Map<String, Integer> msi1 = new LinkedHashMap<>();

msi1.put("hello", 1);
msi1.put("world", 2);
msi1.put("morning", 3);

for(Map.Entry<String, Integer> e : msi1.entrySet()){

    if(e.getKey().equals("world")){

        msi1.remove(e.getKey());
    }
}

System.out.println(msi1);

Error message:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:711)
    at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:744)
    at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:742)
    at JTOCollection.MapInterfaceClass2.main(MapInterfaceClass2.java:33)
Java Result: 1
2 Answers
Related