方法1:使用Iterator,,适合在遍历过程中删除元素推荐使用Iterator;
1
2
3
4
5
6
7Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 2);
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Integer> entry = it.next();
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}方法2:Lambda表达式,可以同时拿到key和value
1
2
3map.forEach((key, value) -> {
System.out.println(key + ":" + value);
});方法3:entrySet遍历,在键和值都需要时使用(最常用)
1
2
3for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}方法4:通过keySet或values来实现遍历
1
2
3
4
5
6
7
8// 遍历map中的键
for (Integer key : map.keySet()) {
System.out.println("key = " + key);
}
// 遍历map中的值
for (Integer value : map.values()) {
System.out.println("key = " + value);
}方法5:通过key获取value
1
2
3
4for (Integer key : map.keySet()) {
System.out.println("key = " + key);
System.out.println("value = " + map.get(key));
}注意:使用map的containsKey,containsValue,equals方法和hashCode方法需要重写