Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a key from HashMap? [duplicate]

Tags:

java

hashmap

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);
    }
}   
like image 452
Lyrical Avatar asked Oct 01 '15 00:10

Lyrical


1 Answers

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> );
like image 189
Kesavamoorthi Avatar answered Sep 28 '22 17:09

Kesavamoorthi