抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

在Java中所有的Map都实现了Map接口,因此所有的Map(如 HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以用以下的方式去遍历。

方法1: 使用Lambda表达式

1
2
3
4
5
6
7
8
9
10
Map<String, String> map = new HashMap<>();
map.put("Java", "Java");
map.put("Python", "Python");

map.forEach((key, value) -> System.out.println("key = " + key + ", value = " + value));

map.forEach((key, value) -> {
System.out.println("key = " + key);
System.out.println("value = " + value);
});

方法2: 在for循环中使用entrySet实现Map的遍历

1
2
3
4
5
6
7
8
9
Map<String, String> map = new HashMap<>();
map.put("Java", "Java");
map.put("Python", "Python");

for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key = " + key + ", value = " + value);
}

方法3: 在for循环中遍历key或者values,一般适用于只需要Map中的key或者value时使用,在性能上比使用entrySet较好

1
2
3
4
5
6
7
8
9
10
11
Map<String, String> map = new HashMap<>();
map.put("Java", "Java");
map.put("Python", "Python");

for (String key : map.keySet()) {
System.out.println("key = " + key);
}

for (String value : map.values()) {
System.out.println("value = " + value);
}

方法4: 通过Iterator遍历

1
2
3
4
5
6
7
8
9
10
11
Map<String, String> map = new HashMap<>();
map.put("Java", "Java");
map.put("Python", "Python");

Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key = " + key + ", value = " + value);
}

方法5: 通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作

1
2
3
4
5
6
7
8
Map<String, String> map = new HashMap<>();
map.put("Java", "Java");
map.put("Python", "Python");

for (String key : map.keySet()) {
String value = map.get(key);
System.out.println("key = " + key + ", value = " + value);
}