Java遍历Map的五种方式

Java遍历Map可以有以下五种方式。根据不同的场景,我们可以选择不同的遍历方式。

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapTest {
    public static void main(String[] args) {
        Map<String, String> countryMap = new HashMap<>();
        countryMap.put("1", "中国");
        countryMap.put("2", "美国");
        countryMap.put("3", "俄罗斯");
        countryMap.put("4", "英国");
        countryMap.put("5", "法国");

        // Map遍历方式一:通过values()遍历所有的value,缺点是不能遍历key。
        System.out.println("Map遍历方式一");
        for (String value : countryMap.values()) {
            System.out.println(value);
        }

        // Map遍历方式二:先获取key,再通过key取value。
        System.out.println("Map遍历方式二");
        for (String key : countryMap.keySet()) {
            System.out.println(key + ":" + countryMap.get(key));
        }

        // Map遍历方式三:先获取Map.entrySet的迭代器,再通过iterator遍历
        System.out.println("Map遍历方式三");
        Set<Map.Entry<String, String>> entries = countryMap.entrySet();
        Iterator<Map.Entry<String, String>> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + ":" + value);
        }

        // Map遍历方式四:推荐。相比于方式三需要获取个迭代器,更方便高效。
        System.out.println("Map遍历方式四");
        for (Map.Entry<String, String> entry : countryMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + ":" + value);
        }

        // Map遍历方式五:JDK8的新增的遍历方式。->是Java 8 Lambda 表达式,感兴趣的可自行百度学习。
        System.out.println("Map遍历方式五");
        countryMap.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });
        
    }
}

打印结果:

Map遍历方式一
中国
美国
俄罗斯
英国
法国
Map遍历方式二
1:中国
2:美国
3:俄罗斯
4:英国
5:法国
Map遍历方式三
1:中国
2:美国
3:俄罗斯
4:英国
5:法国
Map遍历方式四
1:中国
2:美国
3:俄罗斯
4:英国
5:法国
Map遍历方式五
1:中国
2:美国
3:俄罗斯
4:英国
5:法国

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

架构帅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值