老司机怎么遍历Map?

老司机怎么遍历Map?

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

  • 方法一:在for循环中使用Entry实现Map的遍历:


<code>/**
* 最常见也是大多数情况下用的最多的,一般在键值对都需要使用
*/
Map <string>map = new HashMap<string>();
map.put("Spring技术内幕", "计文柯");
map.put("架构探险", "黄勇");
for(Map.Entry<string> entry : map.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey+":"+mapValue);
}
/<string>/<string>/<string>/<code>
  • 方法二:在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好;


<code>Map <string>map = new HashMap<string>();
map.put("Spring技术内幕", "计文柯");
map.put("架构探险", "黄勇");
//key
for(String key : map.keySet()){

System.out.println(key);
}
//value
for(String value : map.values()){
System.out.println(value);
}
/<string>/<string>/<code>
  • 方法三:通过Iterator遍历;


<code>Iterator<entry>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Entry<string> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
/<string>/<entry>/<code>
  • 方法四:通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作;


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


总结

如果绝大多数数据都要用到,那么我们最好使用Entry来遍历,像方法四,每次都拿着key去map里查一次value,开销是比较大的。


分享到:


相關文章: