JDK8 Map 新方法之computeIfAbsent

在JDK8中,Map多了一些新的方法,这里首先介绍computeIfAbsent。

default V computeIfAbsent(K key, Function <? super K,? extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

如果指定的key还没有和一个value关联起来(或者这个key被映射到了null),那么就用给定的映射函数计算出value,如果计算出的值不是null的话,就将其插入map。

If the function returns null no mapping is recorded. If the function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded. The most common usage is to construct a new object serving as an initial mapped value or memoized result

如果函数返回的是null,不会记录下映射关系;如果函数本身抛出了一个(unchecked)异常,这个异常被重新抛出,同样不会记录下映射关系。最常见的用途是构造一个新的对象,作为Map的一个初始映射值,或者用于记录结果:

map.computeIfAbsent(key, k -> new Value(f(k)));

或者实现一个多值Map,Map<K,Collection<V>>, 支持将每个key映射到多个值:

 map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);

在实际应用中该方法可以简化代码,例如在java7:

        Map<Integer, List<Integer>> indices = new HashMap<>();

        for(int i=0; i<nums.length;i++){
            if(indices.containsKey(nums[i])){
                indices.get(nums[i]).add(i);
            }else{
                List<Integer> list = new ArrayList<>();
                list.add(i);
                indices.put(nums[i], list);
            }
        }

在jdk8中,可以简化为

        Map<Integer, List<Integer>> indices = new HashMap<>();
        for(int i=0; i<nums.length;i++){
            indices.computeIfAbsent(nums[i], x->new ArrayList<Integer>()).add(i);
        }

computeIfAbsent

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,136评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,143评论 0 13
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,420评论 0 23
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 7,593评论 0 3
  • 最近天气凉下来了,温暖的被窝总是不愿放手,早上起得比夏天的时候晚了不少。老远就望见教室黑压压的一片,前排已经坐满了...
    竹个个阅读 4,125评论 0 1