Map的四種遍歷方式


首先說一下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);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM