首先說一下Map.entrySet()這個方法,Map.entrySet()返回的是一個Set<Map.Entry<K,V>>,Map.Entry是Map中的一個接口,Map.Entry是Map中的一個映射項(key,value),而Set<Map.Entry<K,V>>是映射項的Set集合.Map.Entry里有相應的getKey和getValue方法,即javaBean,讓我們能夠從一個項中取出key和value.
下面用代碼寫一下Map遍歷的四種方式
public static void main(){
Map<String,String> map = new HashMap();
map.put("1","value1");
map.put("2"."value2");
map.put("3","value3");
}
1.利用map.keySet()方法獲取所有key的集合,然后通過map.get(key)獲取value
for(String key : map.keySet()){
System.out.println(map.get(key));
}
2.利用Map.entrySet()獲取Set遍歷,然后利用Iterator()遍歷進行獲取
Iterator<Map.Entry<String,String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String,String> entry = it.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
3.這種方法是推薦的(網上說適合容量較大時的遍歷,原因:只遍歷的一遍就把所需的key以及value的值放入entrySet,而keySet需要遍歷兩遍,第一遍是獲取所有key,第二遍是get(key)遍歷一遍)
for(Map.entrySet<String,String> entry:map.entrySet()){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
4.利用map.values() 遍歷所有value的值,但是不能遍歷到key
for(String value : map.values()){
System.out.println(value);
}