天天看點

Map周遊的四種方式Map周遊的四種方式

Map周遊的四種方式

首先 建立一個Map

Map<String, String> map = new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
           

第一種方式:使用 Map.KeySet() ,二次取值 效率比第二種第三種慢一倍

for(String key:map.KeySet()){
    System.out.println(key+map.get(Key));
}
           

第二種方式(推薦):通過Map.entrySet周遊Key和Value(無法在for循環時實作remove等操作)

for(Map.Entry<String,String> entry:map.entrySet()){
    System.out.println(entry.getKey()+entry.getValue());
}
           

第三種方式: 通過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(entry.getKey(),entry.getValue());
}
           

第四種:隻能擷取Value:不能擷取Key

for(String v:map.values()){
    System.out.println(v);
}
           

注意:

Map.entrySet疊代器會生成EntryIterator,其傳回的執行個體是一個包含key/value鍵值對的對象。而keySet中疊代器傳回的隻是key對象,還需要到map中二次取值。故entrySet要比keySet快一倍左右。