李锋镝的博客

  • 首页
  • 时间轴
  • 留言
  • 插件
  • 左邻右舍
  • 关于我
    • 关于我
    • 另一个网站
    • 我的导航站
  • 赞助
Destiny
自是人生长恨水长东
  1. 首页
  2. 转载
  3. 技术
  4. 正文

Java之五种遍历Map集合的方式

2021年2月19日 18359点热度 1人点赞 0条评论

摘要:在java中所有的map都实现了Map接口,因此所有的Map都可以用以下的方式去遍历。

在java中所有的map都实现了Map接口,因此所有的Map都可以用以下的方式去遍历。这篇文章主要给大家介绍了关于Java中遍历Map集合的5种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面一起学习学习吧。

方式一 通过Map.keySet使用iterator遍历

@Test
public void testHashMap1() {
    Map<Integer, String> map = new HashMap<>();
    map.put(001, "Java");
    map.put(002, "数据库");
    map.put(003, "Vue");
    System.out.println(map);

    // 通过Map.keySet使用iterator遍历key,然后通过key得到对应的value值
    Iterator<Integer> iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
        Integer key = iterator.next();
        String value = map.get(key);
        System.out.println("key = " + key + ", value = " + value);
    }
}

结果:

{1=Java, 2=数据库, 3=Vue}
key = 1, value = Java
key = 2, value = 数据库
key = 3, value = Vue

方式二 通过Map.entrySet使用iterator遍历

@Test
public void testHashMap2() {
    Map<Integer, String> map = new HashMap<>();
    map.put(001, "Java");
    map.put(002, "数据库");
    map.put(003, "Vue");
    System.out.println(map);

    // 通过Map.entrySet使用iterator遍历key和value;注意 Set entrySet():返回所有key-value对构成的Set集合
    Iterator<Map.Entry<Integer, String>> entries = map.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<Integer, String> entry = entries.next();
        System.out.println(entry);
    }
}

结果:

{1=Java, 2=数据库, 3=Vue}
1=Java
2=数据库
3=Vue

方式三 通过Map.keySet遍历

@Test
public void testHashMap3() {
    Map<Integer, String> map = new HashMap<>();
    map.put(001, "Java");
    map.put(002, "数据库");
    map.put(003, "Vue");
    System.out.println(map);

    // 通过Map.keySet遍历key,然后通过key得到对应的value值
    for (Integer key : map.keySet()) {
        System.out.println("key = " + key + ", value = " + map.get(key));
    }
}

结果:

{1=Java, 2=数据库, 3=Vue}
key = 1, value = Java
key = 2, value = 数据库
key = 3, value = Vue

方式四 通过For-Each迭代entries,使用Map.entrySet遍历

@Test
public void testHashMap4() {
    Map<Integer, String> map = new HashMap<>();
    map.put(001, "Java");
    map.put(002, "数据库");
    map.put(003, "Vue");
    System.out.println(map);

    // 使用For-Each迭代entries,通过Map.entrySet遍历key和value
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
        System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
    }
}

结果

{1=Java, 2=数据库, 3=Vue}
key = 1, value = Java
key = 2, value = 数据库
key = 3, value = Vue

方式五 使用lambda表达式forEach遍历

@Test
public void testHashMap5() {
    Map<Integer, String> map = new HashMap<>();
    map.put(001, "Java");
    map.put(002, "数据库");
    map.put(003, "Vue");
    System.out.println(map);

  // 使用lambda表达式forEach遍历
    map.forEach((k, v) -> System.out.println("key = " + k + ", value = " + v));
}

forEach 源码

default void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action);
    for (Map.Entry<K, V> entry : entrySet()) {
        K k;
        V v;
        try {
            k = entry.getKey();
            v = entry.getValue();
        } catch(IllegalStateException ise) {
            // this usually means the entry is no longer in the map.
            throw new ConcurrentModificationException(ise);
        }
        action.accept(k, v);
    }
}

从源码可以看到,这种新特性就是在传统的迭代方式上加了一层壳,但是让代码变得更加简单。(开发中推荐使用)

总结

推荐使用 entrySet 遍历 Map 类集合 KV (文章中的第四种方式),而不是 keySet 方式进行遍历。

keySet 其实是遍历了 2 次,第一次是转为 Iterator 对象,第二次是从 hashMap 中取出 key 所对应的 value值。而 entrySet 只是遍历了一次,就把 key 和 value 都放到了 entry 中,效率更高。

values()返回的是 V 值集合,是一个 list 集合对象;keySet()返回的是 K 值集合,是一个 Set 集合对象;entrySet()返回的是 K-V 值组合集合。

如果是 JDK8,推荐使用Map.forEach 方法(文章中的第五种方式)。

 

本文转载自作者: 扬帆向海   原文链接: https://zhangxy.blog.csdn.net/article/details/113336560

除非注明,否则均为李锋镝的博客原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.lifengdi.com/transport/2490

相关文章

  • ThreadLocal如何解决内存泄漏问题
  • SpringBoot定时任务 - 经典定时任务设计:时间轮(Timing Wheel)案例和原理
  • @Resource 和 @Autowired 的区别
  • Spring Boot 2.x使用PostgreSQL数据库
  • 带颜色的JVM:三色标记详解
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: JAVA Map
最后更新:2021年2月19日

李锋镝

既然选择了远方,便只顾风雨兼程。

打赏 点赞
< 上一篇
下一篇 >

文章评论

1 2 3 4 5 6 7 8 9 11 12 13 14 15 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 57 58 60 61 62 63 64 65 66 67 69 72 74 76 77 78 79 80 81 82 85 86 87 90 92 93 94 95 96 97 98 99
取消回复

COPYRIGHT © 2025 lifengdi.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Dylan

津ICP备2024022503号-3