美文网首页
瞧瞧1.8中HashMap增加了哪些好用的API

瞧瞧1.8中HashMap增加了哪些好用的API

作者: 我有一只喵喵 | 来源:发表于2021-04-09 09:33 被阅读0次

一、新增API总览

这里先大致分类列一下1.8中新增的API。

取值相关API

  • getOrDefault(Object key, V defaultValue)
  • forEach(BiConsumer<? super K, ? super V> action)

更新值相关API

  • replaceAll(BiFunction<? super K, ? super V, ? extends V> function)
  • remove(Object key, Object value)
  • replace(K key, V oldValue, V newValue)
  • replace(K key, V value)

设值相关API

  • putIfAbsent(K key, V value)
  • computeIfAbsent(K key,Function<? super K, ? extends V> mappingFunction)
  • computeIfPresent(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)
  • compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)
  • merge(K key, V value,BiFunction<? super V, ? super V, ? extends V> remappingFunction)

二、取值相关

  • getOrDefault(Object key, V defaultValue)
    顾名思义,当指定key不存在的时候,就返回我们传入的默认值,否则返回key对应的value。
    @Test
    public void testGetOrDefault() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        Assert.assertEquals("value2", hashMap.getOrDefault("key2", "value2"));
    }
  • forEach(BiConsumer<? super K, ? super V> action)
    这个也比较简单,就是遍历Entry。
    @Test
    public void testForEach(){
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        hashMap.put("key2", "value2");
        hashMap.forEach((key,value)->{
            System.out.println(key+"---"+value);
        });
    }

三 更新值相关API

  • replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

这里其实就是针对Map的所有Entry对进行遍历,将key,value作为参数调用function,并且将function返回的值设置为当前Entry的value。

    @Test
    public void testReplaceAll() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        hashMap.put("key2", "value2");
        hashMap.replaceAll((key, value) -> "newValue");
        hashMap.forEach((key, value) -> {
            System.out.println(key + "---" + value);
        });
    }

输出:

key1---newValue
key2---newValue
  • replace(K key, V oldValue, V newValue)

当指定key的位置存在,且对应的值是oldValue的时候,那么将此key的值设置为newValue,也是属于简化了一些常用写法,比如我们以前可能经常代码中有以下这种写法来实现在这个功能:

        if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
            map.put(key, newValue);
            return true;
        } else {
            return false;
        }

那么有了这个API之后,一句话完事,其返回了是否替换成功:

    @Test
    public void testReplace() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        hashMap.put("key2", "value2");
        boolean replace = hashMap.replace("key1", "value1", "newValue");
        System.out.println("replace result:" + replace + " --" + hashMap.get("key1"));
    }

输出:

replace result:true --newValue
  • replace(K key, V value)

当存在key时,不管其对应的值是啥,直接将其值设置为value,和上面的类似,也是简化了类似下面这种我们经常使用的操作:

        if (map.containsKey(key)) {
            return map.put(key, value);
        } else {
            return null;
        }

有了这个API之后,也是一句话完事,若key不存在直接返回null,存在的话,替换value之后,返回旧的value:

    @Test
    public void testReplace() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        hashMap.put("key2", "value2");
        String oldValue = hashMap.replace("key1", "value1111");
        System.out.println("oldValue:" + oldValue);
        System.out.println("newValue:" + hashMap.get("key1"));
    }

输出:

oldValue:value1
newValue:value1111

四、设值相关API

  • putIfAbsent(K key, V value)

仅当key不存在,或者key对应的值为NULL时,将此key的值设置为value,并且返回旧值。等同于:

       V v = map.get(key);
        if (v == null) {
            v = map.put(key, value);
        }

        return v;

那么现在提供了新的API,一行代码搞定:

    @Test
    public void testPutIfAbsent() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.putIfAbsent("key1","value1");
        System.out.println(hashMap.get("key1"));
    }
  • computeIfAbsent(K key,Function<? super K, ? extends V> mappingFunction)

当key不存在或者key对应的值为NULL时,那么就拿mappingFunction返回的值(如果这个返回值是也是NULL,则不设置)作为value设置给这个key。这个效果等同于如下代码:

      if (map.get(key) == null) {
            V newValue = mappingFunction.apply(key);
            if (newValue != null) {
                map.put(key, newValue);
            }
        }

那么提供了新的API,会更加简单直观:

    @Test
    public void testComputeIfAbsent() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.computeIfAbsent("key1", key -> {
            //对key进行一些特殊计算
            return "newValue";
        });
        System.out.println(hashMap.get("key1"));
    }
  • computeIfPresent(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)

仅当指定key存在,并且其值不为NULL的时候,将其值更新为remappingFunction返回的值,如果remappingFunction返回了一个null值,则会将这个key给移除掉,等同于如下代码:

        if (map.get(key) != null) {
            V oldValue = map.get(key);
            V newValue = remappingFunction.apply(key, oldValue);
            if (newValue != null) {
                map.put(key, newValue);
            } else {
                map.remove(key);
            }
        }

使用新API来达到相同目的:

    @Test
    public void testComputeIfPresent() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.putIfAbsent("key1", "value1");
        hashMap.computeIfPresent("key1", (key,value) -> {
            //对key进行一些特殊计算
            return "newValue";
        });
        System.out.println(hashMap.get("key1"));
    }
  • compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)

如果指定key不存在,或者其值为NULL,如果remappingFunction返回的值不为null,就将此返回值设置为指定key的value,否则什么也不做;如果指定key存在并且其值不为NULL,如果remappingFuntion返回的值不为null,就将此返回值更新到指定的key上,否则将此key删除。其效果等同于下面代码:

        V oldValue = map.get(key);
        V newValue = remappingFunction.apply(key, oldValue);
        if (oldValue != null) {
            if (newValue != null) {
                map.put(key, newValue);
            } else {
                map.remove(key);
            }
        } else {
            if (newValue != null) {
                map.put(key, newValue);
            } else {
                return null;
            }
        }

使用新API后的效果:

    @Test
    public void testCompute() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        hashMap.compute("key1", (key, value) -> {
            // 如果返回null,则此key被删除
            return null;
        });
        Assert.assertNull(hashMap.get("key1"));
        hashMap.put("key1", "value1");
        hashMap.compute("key1", (key, value) -> {
            // 如果返回null,则此key被删除
            return "newValue";
        });
        Assert.assertEquals(hashMap.get("key1"), "newValue");

    }
  • merge(K key, V value,BiFunction<? super V, ? super V, ? extends V> remappingFunction)

如果指定key不存在,或者其值是NULL的时候,则直接将入参value设置为指定key的值,否则的话,会传入key对应值oldValue以及当前merge入参的value给remappingFunction,假如remappingFunction返回的值不是NULL,则更新此返回值为指定key的新值,否则就将此key移除掉。其效果等同于:

      V oldValue = map.get(key);
        V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value);
        if (newValue == null) {
            map.remove(key);
        } else {
            map.put(key, newValue);
        }

使用新API后,就显得更要简洁:

    @Test
    public void testMerge() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        hashMap.merge("key1", "newValue", (oldValue, newValue) -> {
            return oldValue + "-" + newValue;
        });
        Assert.assertEquals(hashMap.get("key1"),"value1-newValue");
    }

相关文章

  • 瞧瞧1.8中HashMap增加了哪些好用的API

    一、新增API总览 这里先大致分类列一下1.8中新增的API。 取值相关API getOrDefault(Obje...

  • HashMap

    1.HashMap数据结构 JDK1.7,HashMap由数组和链表组成;JDK1.8,HashMap中增加了红黑...

  • 四、核心数据结构Map

    注意的是:HashMap里的Entry结构只有next,是单链表 继承了HashMap的Node结构,增加了bef...

  • HashMap的小秘密

    Api文档里说: An instance of HashMap has two parameters that a...

  • API 设计随谈

    思考角度 api 使用者往往只关注,简单好用,越好用的api,越是感受不到它良好的设计存在。自然无感 api 设计...

  • 各种杂记想到就记

    1. SparseArray 是Android特有的API比HashMap节省内存正序插入效率高于HashMap,...

  • HashMap

    HashMap是数组+链表+红黑树。 Node.hash是key的hash1.8的HashMap增加了红黑树来增加...

  • HashMap 高级(一)

    API 1. HashMap结合简介 HashMap基于哈希表的Map接口实现,是以key-value存储形式存在...

  • Android使用SparseArray取代HashMap

    开发中,HashMap使用非常频繁,而HashMap是Java官方API,针对Android移动平台,性能并不合适...

  • java api系列之HashMap

    java api系列目录 java api系列 java api系列之HashMap 简述 首先看一下官方文档是怎...

网友评论

      本文标题:瞧瞧1.8中HashMap增加了哪些好用的API

      本文链接:https://www.haomeiwen.com/subject/fpaykltx.html