【JAVA8新特性】- Map中的computeIfAbsent方法

Map中的computeIfAbsent方法是方法更简洁。

在JAVA8的Map接口中,增加了一个方法computeIfAbsent,此方法签名如下:

public V computeIfAbsent(K key, Function mappingFunction)

此方法首先判断缓存MAP中是否存在指定key的值,如果不存在,会自动调用mappingFunction(key)计算key的value,然后将key = value放入到Map。
如果mappingFunction(key)返回的值为null或抛出异常,则不会有记录存入map

Example01

        Map map = new HashMap<>();

        // 原来的方法
        if (!map.containsKey("huawei")) {
            map.put("huawei", "huawei" + "华为");
        }

        // 同上面方法效果一样,但更简洁
        map.computeIfAbsent("huawei", k -> k + "华为");

        System.out.println(map);

Example02

        Map map2 = new HashMap<>();
        // 统计字段出现个数
        List list = Lists.newArrayList("h", "e", "l", "l", "o", "w", "o", "r", "l", "d");
        for (String str : list) {
            map2.computeIfAbsent(str, k -> new AtomicInteger()).getAndIncrement();
        }
        // 遍历
        map2.forEach((k, v) -> System.out.println(k + " " + v));

Example03

        Map> map3 = new HashMap<>();

        // 如果key不存在,则创建新list并放入数据;key存在,则直接往list放入数据
        map3.computeIfAbsent("ProgrammingLanguage", k -> new ArrayList<>()).add("Java");
        map3.computeIfAbsent("ProgrammingLanguage", k -> new ArrayList<>()).add("Python");
        map3.computeIfAbsent("ProgrammingLanguage", k -> new ArrayList<>()).add("C#");
        map3.computeIfAbsent("Database", k -> new ArrayList<>()).add("Mysql");
        map3.computeIfAbsent("Database", k -> new ArrayList<>()).add("Oracle");

        // 遍历
        map3.forEach((k, v) -> System.out.println(k + " " + v));

你可能感兴趣的:(【JAVA8新特性】- Map中的computeIfAbsent方法)