在java中所有的map都实现了Map接口,因此所有的Map(如HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以用以下的方式去遍历。
定义测试map
public static Map<String, String> map() {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 10000; i++) {
map.put("key_" + i, "value_" + i);
}
return map;
}
方法一:在for循环中使用entries实现Map的遍历:
public static void main(String[] args) {
Map<String, String> map = map();
for (Map.Entry<String, String> entry : map.entrySet()) {
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey + ":" + mapValue);
}
}
方法二:在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好;
public static void main(String[] args) {
Map<String, String> map = map();
//key
for(String key : map.keySet()){
System.out.println(key);
}
//value
for(String value : map.values()){
System.out.println(value);
}
}
方法三:通过Iterator遍历;
public static void main(String[] args) {
Map<String, String> map = map();
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);
}
}
方法四:通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作;
public static void main(String[] args) {
Map<String, String> map = map();
for(String key : map.keySet()){
String value = map.get(key);
System.out.println(key+":"+value);
}
}
本文详细介绍了在Java中遍历Map的四种常见方法,包括使用entries、key或values、Iterator以及通过键找值的方式,并对比了它们的性能特点。

498

被折叠的 条评论
为什么被折叠?



