Map遍歷的幾種方法spa
Map<String,String> map = new HashMap<String, String>(); map.put("item1", "value1"); map.put("item2", "value2"); map.put("item3", "value3"); map.put("item4", "value4"); map.put("item5", "value5");
System.out.println(map.hashCode()); //第三種 廣泛使用,二次取值 經過Map.keySet遍歷key和value: for(String key:map.keySet()){ System.out.println(key+"/"+map.get(key)); } System.out.println("---------------------------------"); //第四種 經過Map.values()遍歷全部的value,但不能遍歷key for(String v:map.values()){ System.out.println("value:"+v); } System.out.println("---------------------------------"); //第二種遍歷方法 推薦,尤爲是容量大時 for(Map.Entry<String, String> entry:map.entrySet()){ System.out.println(entry.getKey()+"/"+entry.getValue()); } System.out.println("---------------------------------"); //第一種遍歷方法 Set<String> set = map.keySet(); Iterator<String> it = set.iterator(); while(it.hasNext()){ String str = it.next(); System.out.println(str+"/"+map.get(str)); } System.out.println("+++++++++++++++++++++"); Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<String, String> entry = iterator.next(); System.out.println(entry.getKey()+"/"+entry.getValue()); }