There are a few solutions for looping a HashMap, but one of the most elegant looks like below:
02. map.put("One", 1); 03. map.put("Two", 2); 04. map.put("Three", 3); 05. map.put("Four", 4); 06. map.put("Five", 5); 07. map.put("Six", 6); 08. map.put("Seven", 7); 09. map.put("Eight", 8); 10. map.put("Nine", 9); 11. map.put("Ten", 10); 12. 13. for (Map.Entry<String, Integer> entry : map.entrySet()) { 14. System.out.println(map.getKey() + " " + map.getValue()); 15. } 2. if(entry.getValue() > 5){ 3. map.remove(entry.getKey()); 4. } 5.}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:
1.for(Iterator<Map.Entry<String,Integer>>it=map.entrySet().iterator();it.hasNext();){ 2. Map.Entry<String, Integer> entry = it.next(); 3. if (entry.getValue() > 5) { 4. it.remove(); 5. } 6. } Reference
No comments:
Post a Comment