Java集合学习总结-----Map集合遍历的主要方式

Map集合的遍历的几种方式

数据准备
Map<String,Integer> map = new HashMap<>();
map.put("Tom",22);
map.put("Jack",20);
map.put("Lucy",18);
1.toString()遍历
System.out.println("toString遍历:");
System.out.println(map);
2.借助keySet方法,通过二次取值遍历
System.out.println("二次取值遍历:");
for(String key : map.keySet()){
    System.out.printf("%s=%d %c",key,map.get(key),',');
}
System.out.println();
3.迭代器遍历
System.out.println("通过entrySet方法加迭代器遍历:");
Iterator<Map.Entry<String,Integer>> iterator =  map.entrySet().iterator();
while(iterator.hasNext()){
    System.out.print(iterator.next() + ",");
}
System.out.println();
4.增强型for循环遍历
System.out.println("通过增强型for循环遍历:");
for(Map.Entry<String,Integer> temp : map.entrySet()){
    System.out.print(temp + ",");
}
5.forEach遍历
System.out.println("forEach遍历:");
map.forEach((key,value) -> System.out.print(key + "=" + value + ","));
执行结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43213517/article/details/89525205