1.通过接收keySet来遍历:
HashMap<String,String> map = new HashMap<>();
map.put("bb","12");
map.put("aa","13");
for(String each:map.keySet()){
System.out.println("key:"+each+"value:"+map.get(each));
}
输出为:
2,通过entrySet来遍历
for(Map.Entry<String,String> each:map.entrySet()){
System.out.println("key:"+each.getKey()+" value:"+each.getValue());
}
输出为:
3.使用迭代器遍历(实质上foreach语句就是迭代器实现)
Iterator test01 = map.entrySet().iterator();
while(test01.hasNext()){
System.out.println(test01.next());
}
输出为:
4.通过valueSet来遍历(只能遍历到值,但是hashMap是加入有序的,所以不用担心和加入顺序不一样)
for(String each:map.values()){
System.out.println(each);
}
输出为:
希望对大家有所帮助