话不多说,上代码,要点在注释上,仔细看!!!
@Test
public void testIteraMap(){
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "1");
map.put(2, "2");
map.put(3, "3");
map.put(4, "4");
map.put(5, "5");
//遍历map集合
//1.遍历键,通过键取值
Set s =map.keySet();
for(Object ss : s){
System.out.print(map.get(ss));
}
System.out.println();
//2.通过iterator遍历map的EntrySet
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer, String> entry = iterator.next();
System.out.print(entry.getKey()+":"+entry.getValue()+" ");
}
System.out.println();
//3.使用foreach遍历map的EntrySet 这种方法和第二种方法可以在map容量较大的时候使用。
//上次在介绍list时已经说过foreach和iterator方法时遍历次数多时,遍历效率最高的,在这里同样适用,因为遍历map的本质还是遍历数组。
for(Map.Entry<Integer, String> entry:map.entrySet()){
System.out.print(entry.getKey()+":"+entry.getValue()+" ");
}
System.out.println();
//4.还使用map的values方法获取所有的values 此方法不建议使用,因为获取不到map的键,在实际应用中导致对应混乱。
}