高效使用Map的“新”方法

个人名片:
😊作者简介:一个为了让更多人看见许舒雅的宝贝的小白先生
🤡个人主页:🔗 许舒雅的宝贝
🐼座右铭:深夜两点半的夜灯依旧闪烁,凌晨四点的闹钟不止你一个。
🎅学习目标: 坚持前端的学习进度,做一个全栈开发工程师

Map的数据操作,你是不是还只会put、get方法?

Map是我们日常变成中十分常用的数据接口,在JDK8中,Map引入了几个新方法,可以简化我们在实际写代码过程中对Map的数据操作。

目录

🌟1.getOrDefault方法

🌟2. foreach

🌟3.merge

🌟4.putIfAbsent

🌟5.computer

🌟6.computeIfAbsent

🌟7.computeIfPresent


🌟1.getOrDefault方法

使用 getOrDefault 方法获取键为 "key1" 的值,如果不存在则返回默认值 "defaultValue"

public class MapTest {

    public static void main(String[] args) {
        // 测试 put() 方法
        testGetOrDefault();
    }

    private static void testGetOrDefault() {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");

        // 使用 getOrDefault 方法获取键为 "key1" 的值,如果不存在则返回默认值 "defaultValue"
        String value = map.getOrDefault("key3", "defaultValue");
        System.out.println(value); // 输出: value1
    }
}

🌟2. foreach

使用 forEach 方法遍历 Map 中的键值对

    public static void main(String[] args) {
        // 测试 testGetOrDefault() 方法
        // testGetOrDefault();
        // 测试testForeach()方法
        testForeach();
    }

    private static void testForeach() {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");

        // 使用 forEach 方法遍历 Map 中的键值对
        map.forEach((key, value) -> {
            System.out.println("Key: " + key + ", Value: " + value);
        });
    }
}

🌟3.merge

使用 merge 方法合并键为 "key1" 的值,如果键不存在则添加新的键值对

    public static void main(String[] args) {
        // 测试 testGetOrDefault() 方法
        // testGetOrDefault();
        // 测试testForeach()方法
        // testForeach();
        // 测试testMerge()方法
        testMerge();
    }

    private static void testMerge(){
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");

        // 使用 merge 方法合并键为 "key1" 的值,如果键不存在则添加新的键值对
        map.merge("key1", "newValue", (oldValue, newValue) -> oldValue + " " + newValue);
        System.out.println(map.get("key1")); // 输出: value1 newValue
    }
}

🌟4.putIfAbsent

putIfAbsent()方法的作用是,如果指定的键不存在于映射中,则将指定的键值对添加到映射中。

    public static void main(String[] args) {
        // 测试 testGetOrDefault() 方法
        // testGetOrDefault();
        // 测试testForeach()方法
        // testForeach();
        // 测试testMerge()方法
        // testMerge();
        // 测试testPutIfAbsent()方法
        testPutIfAbsent();
    }

    //putIfAbsent()方法的作用是,如果指定的键不存在于映射中,则将指定的键值对添加到映射中。
    private static void testPutIfAbsent() {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");

        // 使用 putIfAbsent 方法添加键值对,如果键不存在则添加新的键值对
        map.putIfAbsent("key3", "value3");
        map.putIfAbsent("key2", "newValue");

        System.out.println(map.get("key3")); // 输出: value3
        System.out.println(map.get("key2")); // 输出: value2
    }
}

🌟5.computer

computer()方法的作用是计算指定键的哈希码,并返回计算结果。

computer方法需要传入2个参数:key、function。主要有3步操作

  • 获取到key对应的oldValue,可能为null

  • 经过function计算获取newValue

  • put(key, newValue)

  public static void main(String[] args) {
        // 测试 testGetOrDefault() 方法
        // testGetOrDefault();
        // 测试testForeach()方法
        // testForeach();
        // 测试testMerge()方法
        // testMerge();
        // 测试testPutIfAbsent()方法
        // testPutIfAbsent();
        // 测试testComputer()方法
        testComputer();
    }

    //computer()方法的作用是计算指定键的哈希码,并返回计算结果。
    private static void testComputer() {
        Map<String, Integer> map = new HashMap<>();
        List<String> keys = Arrays.asList("apple","orange","banana","orange");

        for (String itemString : keys) {
            map.compute(itemString, (k,v)->{
                if(v==null){
                    v=1;
                }else{
                    v += 1;
                }
                return v;
            });
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

🌟6.computeIfAbsent

compute方法衍生出来的方法,这个方法只在key不存在的时候,执行computer计算,如果说key对应的value存在,就直接返回这个value。

我们需要计算斐波那锲数列的时候,可以使用这个方法来简化代码

    public static void main(String[] args) {
        // 测试 testGetOrDefault() 方法
        // testGetOrDefault();
        // 测试testForeach()方法
        // testForeach();
        // 测试testMerge()方法
        // testMerge();
        // 测试testPutIfAbsent()方法
        // testPutIfAbsent();
        // 测试testComputer()方法
        // testComputer();
        // 测试testComputeIfAbsent()方法
        testComputeIfAbsent();
    }

    //computeIfAbsent()方法的作用是,如果指定的键不存在于映射中,则将指定的键值对添加到映射中。
    private static void testComputeIfAbsent() {
        Map<Integer,Integer> map = new HashMap<>();
        map.put(0, 1);
        map.put(1, 1);
        System.out.println(fab(5,map));
    }
    private static int fab(int n,Map<Integer,Integer> map){
        return map.computeIfAbsent(n, k->fab(n-1,map)+fab(n-2,map));//n-1和n-2是递归的条件,k是递归的参数,k->fab(n-1,map)+fab(n-2,map)是递归的公式,k是递归的参数,k->fab(n-1,map)+fab(n-2,map)是递归的公式。
    }
}

🌟7.computeIfPresent

computeIfPresent()方法的作用是,如果指定的键存在于映射中,则计算指定键的值,并将计算结果更新到映射中。

    public static void main(String[] args) {
        // 测试 testGetOrDefault() 方法
        // testGetOrDefault();
        // 测试testForeach()方法
        // testForeach();
        // 测试testMerge()方法
        // testMerge();
        // 测试testPutIfAbsent()方法
        // testPutIfAbsent();
        // 测试testComputer()方法
        // testComputer();
        // 测试testComputeIfAbsent()方法
        // testComputeIfAbsent();
        // 测试testComputeIfPresent()方法
        testComputeIfPresent();
    }

    //computeIfPresent()方法的作用是,如果指定的键存在于映射中,则计算指定键的值,并将计算结果更新到映射中。
    private static void testComputeIfPresent() {
        Map<String, Integer> map = new HashMap<>();
        map.put("apple", 1);
        map.put("orange", 2);
        map.put("banana", 3);

        // 使用 computeIfPresent 方法计算指定键的值,并将计算结果更新到映射中
        map.computeIfPresent("apple", (key, value) -> value * 2);
        map.computeIfPresent("orange", (key, value) -> value * 2);
        map.computeIfPresent("banana", (key, value) -> value * 2);

        // 输出更新后的映射
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

 

这篇文章就到这里了,下次见!

🥇原创不易,还希望各位大佬支持一下!

👍点赞,你的认可是我创作的动力 !

🌟收藏,你的青睐是我努力的方向!

✏️评论,你的意见是我进步的财富!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

许舒雅的宝贝

你的鼓励是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值