1. 程式人生 > >java 幾種遍歷map的方法

java 幾種遍歷map的方法

http://blog.csdn.net/bluejoe2000/article/details/39521405

現在定義一個map型別 map<String, Integer>, 需要對其進行遍歷,為方便記憶,可寫如下方法進行遍歷:

Map<String,Integer> map = new HashMap<String, Integer>();
map.put("num1", 1);
map.put("num2", 2);
map.put("num3", 3);
map.put("num3", 3);//是不允許重複的,key值唯一,對應的結果唯一,除非使用IdentityHashMap


1.使用for迴圈,用keySet獲取鍵值:

for(String key:map.keySet()){
			System.out.println("key is :  " + key + " and value is :" + map.get(key));
		}
2.使用map.entryset,使用iterator進行遍歷;
Iterator itor= map.entrySet().iterator();
		
		while(itor.hasNext()){
			Map.Entry<String, Integer> entry = (Entry<String, Integer>) itor.next();
			System.out.println(entry.getKey());
			System.out.println(entry.getValue());
		}


3 使用map.entryset+ for迴圈進行遍歷(推薦,尤其是容量大時):

for(Map.Entry<String, Integer> entry : map.entrySet()){
			System.out.println("this is key :"+entry.getKey() + " this is value:  "  + entry.getValue());
		}
4.只能獲得value的值,通過map.getValue();
for(Integer value:map.values()){
			System.out.println(value);
		}