HashMap的几种遍历方法

目录

一、通过KeySet()方法遍历

二、通过entrySet()方法遍历

三、通过Lambda表达式遍历

四、通过Streams遍历


一、通过KeySet()方法遍历

先通过map.keySet()获取所有键,然后遍历所有键获取对应值,具体代码如下:

public class Test {
    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("a",1);
        map.put("b",2);
        map.put("c",3);
        map.put("d",4);
        //方法一:通过keySet()遍历
        // 1.1 增强for循环遍历
        Set<String> keys = map.keySet();
        for(String s: keys){
            System.out.println("key="+s+" "+"value="+map.get(s));
        }

        // 1.2 iterator遍历
        System.out.println("iterator遍历...");
        Iterator<String> i = keys.iterator();
        while (i.hasNext()){
            String key=i.next();
            System.out.println("key="+key+" "+"value="+map.get(key));
        }
    }
}

二、通过entrySet()方法遍历

map.entrySet()方法返回键值对映射的Set集合,然后遍历这个集合即可。具体代码如下:
public class Test {
    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("a",1);
        map.put("b",2);
        map.put("c",3);
        map.put("d",4);

        //方法二:通过entrySet()方法遍历
        for(Map.Entry<String,Integer> m: map.entrySet()){
            System.out.println("key="+m.getKey()+" "+"value="+m.getValue());
        }
    }
}

三、通过Lambda表达式遍历

JDK1.8之后支持Lambda表达式,具体代码如下:

public class Test {
    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("a",1);
        map.put("b",2);
        map.put("c",3);
        map.put("d",4);

        //方法三:通过Lambda表达式遍历
        map.forEach((key, value) -> {
            System.out.println("key="+key+" "+"value="+value);
        });
    }
}

 

四、通过Streams遍历

JDK1.8之后支持Streams,具体代码如下:

public class Test {
    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("a",1);
        map.put("b",2);
        map.put("c",3);
        map.put("d",4);

        //方法四:通过Streams遍历
        // 4.1 单线程
        map.entrySet().stream().forEach((entry) -> {
            System.out.println("key="+entry.getKey()+" "+"value="+entry.getValue());
        });

        // 4.2 多线程
        System.out.println("Streams API多线程...");
        map.entrySet().parallelStream().forEach((entry) -> {
            System.out.println("key="+entry.getKey()+" "+"value="+entry.getValue());
        });
    }
}

除了 Stream 的并行循环,其他几种遍历方法的性能差别不大,但从简洁性和优雅性上来看,Lambda 和 Stream无疑是最适合的遍历方式。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值