Java中HashMap的循环遍历方式

原文地址

Map的四种遍历方式

(1)for each map.entrySet()

Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
    entry.getKey();
    entry.getValue();
}

(2) 显示调用map.entrySet()的集合迭代器

Iterator.Entry> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry entry = iterator.next();
    entry.getKey();
    entry.getValue();
}

(3) for each map.keySet(),再调用get获取

Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
    map.get(key);
}

(4) for each map.entrySet(),用临时变量保存map.entrySet()

SetString, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
    entry.getKey();
    entry.getValue();
}

你可能感兴趣的:(Java学习)