Map循环遍历的常用方法

本文介绍了在Java编程中,如何使用不同方法遍历Map集合,包括迭代器、键值对、for-each循环等常见方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用Map循环遍历的方法

  Map<String, Object> map = new HashMap<String, Object>();
        map.put("1", "a");
        map.put("2", "b");
        map.put("3", "c");
        System.out.println(map.containsKey("4"));

        //构造测试数据
        List<Map<String, Integer>> list = new ArrayList<>();

        HashMap<String, Integer> map1 = new HashMap<String, Integer>() {
            {
                put("a", 16);
            }
        };
        list.add(map1);
        HashMap<String, Integer> map2 = new HashMap<String, Integer>() {
            {
                put("a", 17);
            }
        };
        list.add(map2);
        HashMap<Strin
Java中,有多种方法可以循环遍历Map。在你提供的引用中,以下是三种常用方法方法一:使用for循环遍历key或者value ```java Map<String, String> map = new HashMap<>(); map.put("第一个对象", "1"); map.put("第二个对象", "2"); // 遍历key for(String mapKey : map.keySet()){ System.out.println(mapKey); } // 遍历value for(String mapValue : map.values()){ System.out.println(mapValue); } ``` 方法二:使用Iterator遍历Map ```java Map<String, String> map = new HashMap<>(); map.put("第一个对象", "1"); map.put("第二个对象", "2"); Iterator iterator = map.keySet().iterator(); while(iterator.hasNext()){ Object mapKey = iterator.next(); System.out.println("key:" + mapKey + ", value:" + map.get(mapKey)); } ``` 方法三:使用entrySet()方法遍历Map ```java Map<String, String> map = new HashMap<>(); map.put("第一个对象", "1"); map.put("第二个对象", "2"); Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator(); while(entries.hasNext()){ Map.Entry<String, String> entry = entries.next(); String mapKey = entry.getKey(); String mapValue = entry.getValue(); System.out.println(mapKey + ":" + mapValue); } ``` 这些方法适用于不同的场景,选择哪种方法取决于你需要遍历Map的具体要求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [[java] Map循环遍历的5种方法实现](https://blog.csdn.net/u010321872/article/details/127364551)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿杰同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值