方式1使用Map.Entry进行遍历
在for循环中使用【Map.Entry】对象实现Map对象的遍历。
public class Test {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ": " + value);
}
}
}
方式2使用Map.keySet进行遍历
通过键值查找的方式进行遍历
public class Test {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
for (Integer key : map.keySet()) {
String value = map.get(key);
System.out.println(key + ": " + value);
}
}
}
方式3使用迭代器(Iterator)进行遍历
可以对两种对象(【Map.entrySet】和【Map.keySet】)使用迭代器进行迭代。
public class Test {
public static void main(String[] args) {
Map<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> entry = iterator.next();
int key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ": " + value);
}
}
}
方式4使用for-each进行遍历
使用 for-each 循环遍历 key 或者 values,一般适用于只需要 Map 中的 key 或者 value 时使用。性能上比 entrySet 较好。
public class Test {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.forEach((k, v) -> System.out.println(k + ": " + v));
}
}
个人总结
- 如果是JDK8,推荐使用方式4进行遍历;
- 最常用方式1进行遍历;
- 使用迭代器的好处在于调用方总是以统一的方式遍历各种集合类型,而不必关心它们内部的存储结构。