老司機怎麼遍歷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,開銷是比較大的。


分享到:


相關文章: