i have this hashmap
HashMap <Integer,Integer> H = new HashMap <Integer,Integer>();
and when i try to remove the key from HashMap i recive this error
**Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:922)
at java.util.HashMap$KeyIterator.next(HashMap.java:956)
at Livre.montantTotal(Livre.java:42)**
this is my code
for (int e : H.keySet()){
H.put(e, H.get(e)-1);
if (H.get(e) == 0){
H.remove(e);
}
}
You are getting this error because you are trying to remove the element and rearrange the hashmap while its already in use (while looping through it).
To loop through an collection objects in Java, you have an Iterator
class which can solve your problem. That class has a remove()
method to remove a key pair value from HashMap
.
Possible duplicate of How to remove a key from HashMap while iterating over it? and
iterating over and removing from a map
EDIT:
Try this code on Java 7 and earlier versions:
Map<String, String> map = new HashMap<String, String>() {
{
put("test", "test123");
put("test2", "test456");
}
};
for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, String> entry = it.next();
if(entry.getKey().equals("test")) {
it.remove();
}
}
In Java 8, you can try this:
map.entrySet().removeIf(e-> <boolean expression> );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With