- 在集合框架的map中,有3個方法,分別是:
- keySet(): 將map中所有的key取出並存放在Set集合中(key的唯一性) Set<K>
- values(): 將map中的所有values取出並存放在一個Collection中(value不唯一) Collection<V>
- entrySet(): 將map中的一組鍵值對key-value視爲一個整體entry,存放在Set<map.Entry<K,V>>
- 所以對應的遍歷map集合也有3種方式:
//第一種:普遍使用,二次取值
System.out.println("通過Map.keySet遍歷key和value:");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//第二種
System.out.println("通過Map.values()遍歷所有的value,但不能遍歷key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}
//第三種:推薦,尤其是容量大時
System.out.println("通過Map.entrySet遍歷key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
****當要對集合執行刪除、插入時,必須要使用Iterator來保證類似事務的操作*****
//這中方法會比第三種方法效率低,但是可以用來保證集合的狀態
System.out.println("通過Map.entrySet使用iterator遍歷key和value:");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
詳情可參考:http://www.cnblogs.com/goody9807/p/6432904.html 對JAVA集合進行遍歷刪除時務必要用迭代器