Platinum Partner
java

Removing entries from a HashMap

There are a few solutions for looping a HashMap, but one of the most elegant looks like below:

HashMap<String, Integer> map = new HashMap<String, Integer>();
  map.put("One", 1);
  map.put("Two", 2);
  map.put("Three", 3);
  map.put("Four", 4);
  map.put("Five", 5);
  map.put("Six", 6);
  map.put("Seven", 7);
  map.put("Eight", 8);
  map.put("Nine", 9);
  map.put("Ten", 10);
        
  for (Map.Entry<String, Integer> entry : map.entrySet()) {
       System.out.println(map.getKey() + "    " + map.getValue());      
  }
Now, that is great, but if you try to remove an entry while looping
  for (Map.Entry<String, Integer> entry : map.entrySet()) {
     if(entry.getValue() > 5){
        map.remove(entry.getKey());
      }
}

an java.util.ConcurrentModificationException will occur!
Solving this issue involves adding an Iterator which conforming to documentation “Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.” will allows us to call remove(). Therefore, here it is:
for(Iterator<Map.Entry<String,Integer>>it=map.entrySet().iterator();it.hasNext();){
     Map.Entry<String, Integer> entry = it.next();
     if (entry.getValue() > 5) {
          it.remove();
     }
 }
Done !

 

From http://e-blog-java.blogspot.com/2011/09/removing-entries-from-hashmap.html

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}