您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,使用Enhanced For Loop(也称为for-each循环)遍历Map集合时,您需要遍历Map的键值对
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// 创建一个Map集合
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// 使用Enhanced For Loop遍历Map集合的键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
在这个示例中,我们首先导入了java.util.HashMap
和java.util.Map
类。然后,我们创建了一个名为map
的HashMap实例,并向其中添加了一些键值对。接下来,我们使用Enhanced For Loop遍历map的entrySet,通过entry.getKey()
和entry.getValue()
分别获取键和值。最后,我们将键和值打印到控制台。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。