0
点赞
收藏
分享

微信扫一扫

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

巧乐兹_d41f 2023-01-03 阅读 85

文章目录

Map集合的遍历方式

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

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

键找值涉及到的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集合的遍历方式二: 键值对

键值对设计到的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

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);
        }
    });
}
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));
}
举报

相关推荐

0 条评论