Java遍历Map对象的方式

时间:2022-11-23 07:34:51
public static void main(String[] args) {
HashMap<String, String> testMap = new HashMap<>();
for (int i = 0; i < 10; i++) {
testMap.put("a" + i, "b" + i);
}
//方式一 这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用。
for (Map.Entry<String, String> entry : testMap.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
} //方法二 在for-each循环中遍历keys或values。
//遍历map中的键
for (String key : testMap.keySet()) {
System.out.println("Key = " + key);
}
//遍历map中的值
for (String value : testMap.values()) {
System.out.println("Value = " + value);
} //方法三使用Iterator遍历
//使用泛型
Iterator<Map.Entry<String, String>> entries1 = testMap.entrySet().iterator();
while (entries1.hasNext()) {
Map.Entry<String, String> entry = entries1.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
//不使用泛型, 可以在遍历时调用iterator.remove()来删除entries
Iterator entries2 = testMap.entrySet().iterator();
while (entries2.hasNext()) {
Map.Entry entry = (Map.Entry) entries2.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
}