遍历HashMap最佳实践

代码实例

使用EntrySetIterator遍历HashMap能具有最佳性能,且在遍历过程中能安全删除元素

@Test  
void testMapIterator() {  
    HashMap<Integer, String> map = new HashMap<>();  
    map.put(1, "a");  
    map.put(2, "b");  
    map.put(3, "c");  
  
    Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();  
    while (iterator.hasNext()) {  
        Map.Entry<Integer, String> next = iterator.next();  
        System.out.println("----------" + next.getKey() + "----------" + next.getValue());  
        iterator.remove();  
    }  
}

输出结果

----------1----------a
----------2----------b
----------3----------c