Map的5种遍历方式

 

Map<String, String> map = new HashMap<String, String>();
map.put("bors", "博士");
map.put("bear2", "熊二");

 

1.entrySet遍历(墙裂推荐!!!)

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

 

2.在for循环中遍历key或者value,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好

复制代码
//key
for (String key : map.keySet()) {
    System.out.println(key);
}
//value
for (String value : map.values()) {
    System.out.println(value);
}
复制代码

 

3.通过Iterator遍历

复制代码
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 + " : " + value);
}
复制代码

 

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

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

 

5.java8 Lambda, 性能低于entrySet,所以更推荐用entrySet的方式

map.forEach((k, v) -> {
    System.out.println(k + " : " + v);
});

 

转自:https://www.cnblogs.com/bors/p/map.html