方法一:使用lambda表达式
Map<Integer, Integer> temp = new HashMap<>();
temp.put(1,1);
temp.put(2,1);
temp.put(3,1);
temp.forEach((k, v) -> System.out.println(v));
其中,k是键,v是值
运行结果:
方法二:使用迭代器遍历
Map<Integer, String> map = new HashMap<>();
map.put(1, "1");
map.put(2, "2");
map.put(3, "3");
Iterator<Map.Entry<Integer, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {Map.Entry<String, Integer> entry = entries.next();System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
运行结果:
方法三:for-each直接遍历
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "1");
map.put(2, "2");
map.put(3, "3");
//遍历map中的键
for (Integer key : map.keySet()) { System.out.println("Key = " + key);
}
//遍历map中的值
for (String value : map.values()) {System.out.println("Value = " + value);
}
运行结果: