Over a million developers have joined DZone.

Removing entries from a HashMap

· Java Zone

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

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

The Java Zone is brought to you in partnership with JetBrains.  Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}