Map<String,String> map = new HashMap<>();
map.put("one","111");
map.put("two","222");
map.put("three","333");
//遍历map推荐使用这种方式
for(Map.Entry<String,String> entry : map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> next = it.next();
System.out.println(next.getKey());
System.out.println(next.getValue());
}
//实际上是遍历map的key
Set<String> keys = map.keySet();
for(String key : keys){
System.out.println(key);
System.out.println(map.get(key));
}
//只能遍历map的值
for(String val : map.values()){
System.out.println(val);
}
map遍历方式
最新推荐文章于 2025-07-21 19:03:31 发布
博客展示了Java中Map的四种遍历方式。包括使用for-each遍历entrySet、使用迭代器遍历entrySet、遍历keySet并通过key获取值,以及直接遍历values。每种方式都有对应的代码示例,可帮助开发者掌握Map遍历技巧。

935

被折叠的 条评论
为什么被折叠?



