Saturday, April 28, 2012

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();
     }
 }

1 comment:

  1. HashMap map = new HashMap();
    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 entry : map.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue());
    }

    ReplyDelete