Removing entries from a HashMap
Join the DZone community and get the full member experience.
Join For FreeThere 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
Opinions expressed by DZone contributors are their own.
Comments