Map遍历方式
KeySet遍历
最低效的遍历形式
大概原理:将Key值集合转为Set,再通过遍历Set然后通过Map取Key值取到Value值
Map map = new HashMap();
map.put("1",11);
map.put("2",22);
Iterator<String>it1 = map.keySet().iterator();
while(it1.hasNext()){
String map1 = it1.next();
System.out.println("map1:"+map1+"\tKEY:"+map1.toString()+"\tValue:"+map.get(map1.toString()));
}
EntrySet 遍历
相对KeySet速度更胜一筹
大概原理:将Key和Value一起转为Set集合,只需通过getKey和getValue取到Key和Value
Map map = new HashMap();
map.put("1",11);
map.put("2",22);
Iterator<Map.Entry<String,Integer>>it2 = map.entrySet().iterator();
while(it2.hasNext()){
Map.Entry<String,Integer> map2 = it2.next();
System.out.println("map2:"+map2+"\tKEY:"+map2.getKey()+"\tValue:"+map2.getValue());
}
1.8后版本遍历形式
Map map = new HashMap();
map.put("1",11);
map.put("2",22);
map.forEach((key,value)->
{
System.out.println("KEY:"+key+"\tValue:"+value);
});