Map 集合的遍歷與 List 和 Set 集合不同。Map 有兩組值,因此遍歷時可以只遍歷值的集合,也可以只遍歷鍵的集合,也可以同時遍歷。Map 以及實現 Map 的接口類(如 HashMap、TreeMap、LinkedHashMap、Hashtable 等)都可以用以下幾種方式遍歷。
1)在 for 循環中使用 entries 實現 Map 的遍歷(最常見和最常用的)。
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("Java入門教程", "http://c.biancheng.net/java/");
map.put("C語言入門教程", "http://c.biancheng.net/c/");
for (Map.Entry<String, String> entry : map.entrySet()) {
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey + ":" + mapValue);
}
}
2)使用 for-each 循環遍歷 key 或者 values,一般適用於只需要 Map 中的 key 或者 value 時使用。性能上比 entrySet 較好。
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("Java入門教程", "http://c.biancheng.net/java/");
map.put("C語言入門教程", "http://c.biancheng.net/c/");
for (Map.Entry<String, String> entry : map.entrySet()) {
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey + ":" + mapValue);
}
}
3)使用迭代器(Iterator)遍歷
Map<String, String> map = new HashMap<String, String>();
map.put("Java入門教程", "http://c.biancheng.net/java/");
map.put("C語言入門教程", "http://c.biancheng.net/c/");
Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
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);
}
