前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >map集合遍历的三种方式(map遍历的两种方式)

map集合遍历的三种方式(map遍历的两种方式)

作者头像
全栈程序员站长
发布2022-08-01 10:01:21
5110
发布2022-08-01 10:01:21
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

Map 集合的遍历与 List 和 Set 集合不同。Map 有两组值,因此遍历时可以只遍历值的集合,也可以只遍历键的集合,也可以同时遍历。Map 以及实现 Map 的接口类(如 HashMap、TreeMap、LinkedHashMap、Hashtable 等)都可以用以下几种方式遍历。

1)在 for 循环中使用 entries 实现 Map 的遍历(最常见和最常用的)。

public static void main(String[] args) {

Map map = new HashMap();

map.put(“Java入门教程”, “http://c.biancheng.net/java/”);

map.put(“C语言入门教程”, “http://c.biancheng.net/c/”);

for (Map.Entry entry : map.entrySet()) {

String mapKey = entry.getKey();

String mapValue = entry.getValue();

System.out.println(mapKey + “:” + mapValue);

}

}

2)使用 for-each 循环遍历 key 或者 values,一般适用于只需要 Map 中的 key 或者 value 时使用。性能上比 entrySet 较好。

Map map = new HashMap();

map.put(“Java入门教程”, “http://c.biancheng.net/java/”);

map.put(“C语言入门教程”, “http://c.biancheng.net/c/”);

// 打印键集合

for (String key : map.keySet()) {

System.out.println(key);

}

// 打印值集合

for (String value : map.values()) {

System.out.println(value);

}

3)使用迭代器(Iterator)遍历

Map map = new HashMap();

map.put(“Java入门教程”, “http://c.biancheng.net/java/”);

map.put(“C语言入门教程”, “http://c.biancheng.net/c/”);

Iterator> entries = map.entrySet().iterator();

while (entries.hasNext()) {

Entry entry = entries.next();

String key = entry.getKey();

String value = entry.getValue();

System.out.println(key + “:” + value);

}

4)通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作。

纯文本复制

for(String key : map.keySet()){

String value = map.get(key);

System.out.println(key+”:”+value);

}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/126894.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年4月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档