Java中Map集合的三种遍历方式

Map集合的遍历方式

Map集合的遍历方式有3种:

方式一:键找值的方式遍历:先获取Map集合全部的键,再根据遍历键找值。

方式二:键值对的方式遍历,把“键值对“看成一个整体,难度较大。

方式三:JDK 1.8开始之后的新技术:Lambda表达式。

Map集合的遍历方式一: 键找值

先通过keySet方法, 获取Map集合的全部键的Set集合。

遍历键的Set集合,然后通过键提取对应值。

键找值涉及到的API:

方法名称 说明
keySet() 获取所有键的集合
get(Object key) 根据键获取值

演示代码:

public static void main(String[] args) {
    Map<String, Integer> maps = new HashMap<>();
    maps.put("华为", 10);
    maps.put("小米", 5);
    maps.put("iPhone", 6);
    maps.put("生活用品", 15);
    maps.put("java", 20);
    maps.put("python", 17);

    // 拿到全部集合的全部键
    Set<String> keys = maps.keySet();
    // 遍历键, 根据键获取值
    for (String key: keys) {
        int value = maps.get(key);
        System.out.println(key + "--->" +value);
    }
}

Map集合的遍历方式二: 键值对

先通过entrySet方法把Map集合转换成Set集合,Set集合中每个元素都是键值对实体类型了(将键和值看成一个整体)。

遍历获取到的Set集合,然后通过getKey提取键, 以及getValue提取值。

键值对设计到的API:

方法名称 说明
Set<Map.Entry<K,V>> entrySet() 获取所有键值对对象的集合
getKey() 获得键
getValue() 获取值

演示代码:

public static void main(String[] args) {
    Map<String, Integer> maps = new HashMap<>();
    maps.put("华为", 10);
    maps.put("小米", 5);
    maps.put("iPhone", 6);
    maps.put("生活用品", 15);
    maps.put("java", 20);
    maps.put("python", 17);

    // 把Map集合转成Set集合
    Set<Map.Entry<String, Integer>> newMaps = maps.entrySet();
    // 遍历转成的Set集合
    for (Map.Entry<String, Integer> newMap : newMaps) {
        String key = newMap.getKey(); // 获取key
        Integer value = newMap.getValue(); // 获取value
        System.out.println(key + "--->" + value);
    }
}

Map集合的遍历方式三: Lambda

得益于JDK 8开始的新技术Lambda表达式,提供了一种更简单、更直接的遍历集合的方式。

Map结合Lambda遍历的API:

方法名称 说明
forEach(BiConsumer<? super K, ? super V> action) 结合lambda遍历Map集合

演示代码:

public static void main(String[] args) {
    Map<String, Integer> maps = new HashMap<>();
    maps.put("华为", 10);
    maps.put("小米", 5);
    maps.put("iPhone", 6);
    maps.put("生活用品", 15);
    maps.put("java", 20);
    maps.put("python", 17);

    // 使用forEach方法遍历对象
    maps.forEach(new BiConsumer<String, Integer>() {
        @Override
        public void accept(String key, Integer value) {
            System.out.println(key + "--->" + value);
        }
    });
}

结合Lambda简化代码

public static void main(String[] args) {
    Map<String, Integer> maps = new HashMap<>();
    maps.put("华为", 10);
    maps.put("小米", 5);
    maps.put("iPhone", 6);
    maps.put("生活用品", 15);
    maps.put("java", 20);
    maps.put("python", 17);

    // 使用forEach方法集合Lambda表达式遍历对象
    maps.forEach((key, value) -> System.out.println(key + "--->" + value));
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>