首页 > 其他 > 详细

遍历map的几种方法

时间:2020-07-04 09:15:55      阅读:43      评论:0      收藏:0      [点我收藏+]

面试被问到了,遍历map有几种方法,记录一下。

 

 

public class MapCollection {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1,"小花");
map.put(2,"小草");
map.put(3,"小红");
map.put(4,"小白");

System.out.println("-----通过Map.keySet()获取key,根据key调用map.get()获取值value------");
for (Integer key:map.keySet()) {
System.out.println(key+":"+map.get(key));
}

System.out.println("-----通过Map.entrySet()获取迭代器对象iterator,遍历key和value-----");
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer, String> entry = it.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}

System.out.println("-----通过Map.entrySet()遍历key和value-------");
for (Map.Entry<Integer,String> entry:map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}

System.out.println("-----通过Map.values()遍历所有的value-----");
System.out.println("-----此方法无法获key----------");
for (String value: map.values()) {
System.out.println(value);
}
}
}

遍历map的几种方法

原文:https://www.cnblogs.com/lifengSkt/p/13233482.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!