前言

得益于 Java 8 的 default 方法特性,Java 8 对 Map 增加了不少实用的默认方法,像 getOrDefault, forEach, replace, replaceAll, putIfAbsent, remove(key, value), computeIfPresent, computeIfAbsent, compute 和merge 方法。另外与 Map 相关的 Map.Entry 也新加了多个版本的 comparingByKey 和 comparingByValue 方法。

为达到熟练运用上述除 getOrDefault 和 forEach 外的其他方法,有必要逐一体验一番,如何调用,返回值以及调用后的效果如何。看看每个方法不至于 Java 8 那么多年还总是  if(map.containsKey(key))... 那样的老套操作。

前注:Map 新增方法对  present 的判断是 map.containsKey(key) && map.get(key) != null,简单就是  map.get(key) != null,也就是即使 key 存在,但对应的值为 null 的话也视为 absent。absent 就是 map.get(key) == null。

不同 Map 实现对 key/value 是否能为 null 有不同的约束, HashMap, LinkedHashMap, key 和 value 都可以为 null 值,TreeMap 的 key 为不能为 null, 但 value 可以为 null, 而 Hashtable, ConcurrentMap 则 key 和 value 都不同为 null。一句话 absent/present 的判断是 map.get(key) 是否为 null。

方法介绍的顺序是它们相对于本人的生疏程度而定的。每个方法介绍主要分两部分,参考实现代码与示例代码执行效果。参考实现代码摘自 JDK 官方的 Map JavaDoc。

putIfAbsent 方法

方法原型 V putIfAbsent(K key, V value) ,  如果 key 不存在或相关联的值为 null, 则设置新的 key/value 值。

参考实现:

  1. V v = get(key);
  2. if (== null) {
  3. = put(key, value);
  4. }
  5. return v;

如果原 map 中对应 key 的值为为 null 返回旧值,或者返回新的 value 值

示例及效果:

  1. String ret;
  2. Map<String, String> map = new HashMap<>();
  3. ret = map.putIfAbsent("a", "aaa"); //ret 为"aaa", map 为 {"a":"aaa"}
  4. ret = map.putIfAbsent("a", "bbb"); //ret 为 "aaa", map 还是 {"a":"aaa"}
  5.  
  6. map.put("b", null);
  7. ret = map.putIfAbsent("b", "bbb"); //ret 为 "bbb", map 为 {"a":"aaa","b":"bbb"}

computeIfPresent 方法

方法原型 V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction),如果指定的 key 存在并且相关联的 value 不为 null 时,根据旧的 key 和 value 计算 newValue 替换旧值,newValue 为 null 则从 map 中删除该 key; key 不存在或相应的值为 null 时则什么也不做,方法的返回值为最终的 map.get(key)。

参考实现:

  1. if (map.get(key) != null) {
  2. V oldValue = map.get(key);
  3. V newValue = remappingFunction.apply(key, oldValue);
  4. if (newValue != null)
  5. map.put(key, newValue);
  6. else
  7. map.remove(key);
  8. }

示例及效果:

  1. String ret;
  2. Map<String, String> map = new HashMap<>();
  3. ret = map.computeIfPresent("a", (key, value) -> key + value); //ret null, map 为 {}
  4. map.put("a", null); //map 为 ["a":null]
  5. ret = map.computeIfPresent("a", (key, value) -> key + value); //ret null, map 为 {"a":null}
  6. map.put("a", "+aaa");
  7. ret = map.computeIfPresent("a", (key, value) -> key + value); //ret "a+aaa", map 为 {"a":"a+aaa"}
  8. ret = map.computeIfPresent("a", (key, value) -> null); //ret 为 null, map 为 {},计算出的 null 把 key 删除了

计算出的值为 null 时直接删除 key 而不是设置对应 key 的值为 null, 这能照顾到值不能为 null 的 Map 实现,如 Hashtable 和 ConcurrentMap。

computeIfAbsent 方法

方法原型 V computeIfAbsent(K key, Function<? super <, ? extends V> mappingFunction), 与上一个方法相反,如果指定的 key 不存在或相关的 value 为 null 时,设置 key 与关联一个计算出的非 null 值,计算出的值为 null 的话什么也不做(不会去删除相应的  key)。如果 key 存在并且对应 value 为 null 的话什么也不做。同样,方法的返回值也是最终的 map.get(key)。

参考实现:

  1. if (map.get(key) == null) {
  2. V newValue = mappingFunction.apply(key);
  3. if (newValue != null)
  4. map.put(key, newValue);
  5. }

示例及效果:

  1. String ret;
  2. Map<String, String> map = new HashMap<>();
  3. ret = map.computeIfAbsent("a", key -> key + "123"); //ret "a123", map 为 {"a":"a123"}
  4. ret = map.computeIfAbsent("a", key -> key + "456"); //ret "a123", map 为 {"a":"a123"}
  5. map.put("a", null);
  6. ret = map.computeIfAbsent("a", key -> key + "456"); //ret "a456", map 为 {"a":"a456"}
  7. ret = map.computeIfAbsent("a", key -> null); //ret 为 "a456", map 为 {"a":"a456"}

replace(K key, V value) 方法

只要 key 存在,不管对应值是否为  null,则用传入的 value 替代原来的值。即使传入的 value 是 null 也会用来替代原来的值,而不是删除,注意这对于 value 不能为  null 值的  Map  实现将会造成 NullPointerException。key 不存在不会修改 Map 的内容,返回值总是原始的 map.get(key) 值。

参考实现:

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

示例及效果:

  1. String ret;
  2. Map<String, String> map = new HashMap<>();
  3. ret = map.replace("a", "abc"); //ret 为 null,map 为 {}
  4. map.put("a", "ddd");
  5. ret = map.replace("a", "abc"); //ret 为 "ddd", map 为 {"a":"abc"}
  6. ret = map.replace("a", null); //ret 为 "abc", map 为 {"a":null}
  7. ret = map.replace("a", "ddd"); //ret 为 null, map 为 {"a":"ddd"}

replace(K key, V oldValue, V newValue)

当且仅当 key 存在,并且对应值与 oldValue 不相等,才用 newValue 作为 key 的新相关联值,返回值为是否进行了替换。

参考实现:

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

示例及效果:

  1. boolean ret;
  2. Map<String, String> map = new HashMap<>() ;
  3. ret = map.replace("a", null, "aaa"); //ret 为 false, map 为 {}
  4. map.put("a", null);
  5. ret = map.replace("a", null, "aaa"); //ret 为 true, map 为 {"a":"aaa"}
  6. ret = map.replace("a", "aaa", null); //ret 为 true, map 为 {"a":null}
  7. ret = map.replace("a", "aaa", "bbb");//ret 为 false, map 为 {"a":null}

replaceAll 方法

方法原型 void replaceAll(BiFunction<? super K, ? super V, ? extends V> function)。它更像一个传统函数型语言的 map 函数,即对于 Map 中的每一个元素应用函数 function, 输入为 key 和  value。

参考实现:

  1. for (Map.Entry<K, V> entry : map.entrySet())
  2. entry.setValue(function.apply(entry.getKey(), entry.getValue()));

示例及效果:

  1. Map<String, String> map = new HashMap<>() ;
  2. map.put("a", "aaa");
  3. map.put("b", "bbb"); //map 为 {"a":"aaa","b":"bbb"}
  4. map.replaceAll((key, value) -> key + "-" + value); //map 为 {"a":"a-aaa","b":"b-bbb"}

remove(key, value)

这个也不用多说,key 与 value 都匹配时才删除。

参考实现:

  1. if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
  2. map.remove(key);
  3. return true;
  4. } else
  5. return false;

compute 方法

方法原型 V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction), 它是 computeIfAbsent 与 computeIfPresent  的结合体。也就是既不管 key 存不存在,也不管 key 对应的值是否为 null, compute 死活都要设置与 key 相关联的值,或者计算出的值为 null 时删除相应的 key, 返回值为最终的 map.get(key)。

参考实现:

  1. V oldValue = map.get(key);
  2. V newValue = remappingFunction.apply(key, oldValue);
  3. if (oldValue != null ) {
  4. if (newValue != null)
  5. map.put(key, newValue);
  6. else
  7. map.remove(key);
  8. } else {
  9. if (newValue != null)
  10. map.put(key, newValue);
  11. else
  12. return null;
  13. }

示例及效果:

  1. String ret;
  2. Map<String, String> map = new HashMap<>() ;
  3. ret = map.compute("a", (key, value) -> "a" + value); //ret="anull", map={"a":"anull"}
  4. ret = map.compute("a", (key, value) -> "a" + value); //ret="aanull", map={"a":"aanull"}
  5. ret = map.compute("a", (key, value) -> null); //ret=null, map={}

merge 方法

方法原型 V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFucntion),这是至今来说比较神秘的一个方法,尚未使用到它。如果指定的 key 不存在,或相应的值为 null 时,则设置  value 为相关联的值。否则根据 key 对应的旧值和 value 计算出新的值 newValue,newValue 为 null 时,删除该key, 否则设置 key 对应的值为  newValue。方法的返回值也是最终的  map.get(key) 值。

参考实现:

  1. V oldValue = map.get(key);
  2. V newValue = (oldValue == null) ? value :
  3. remappingFunction.apply(oldValue, value);
  4. if (newValue == null)
  5. map.remove(key);
  6. else
  7. map.put(key, newValue);

注意 value 不能为 null 值

示例及效果:

  1. String ret;
  2. Map<String, String> map = new HashMap<>() ;
  3. ret = map.merge("a", "aa", (oldValue, value) -> oldValue + "-" + value); //ret="aa", map={"a":"aa"}
  4. ret = map.merge("a", "bb", (oldValue, value) -> oldValue + "-" + value); //ret="aa-bb", map={"a":"aa-bb"}
  5. ret = map.merge("a", "bb", (oldValue, value) -> null); //ret=null, map={}
  6. map.put("a", null);
  7. ret = map.merge("a", "aa", (oldValue, value) -> oldValue + "-" + value); //ret="aa", map={"a":"aa"}
  8. map.put("a", null);
  9. ret = map.merge("a", "bb", (oldValue, value) -> null); //ret="bb", map={"a":"bb"}
  10. ret = map.merge("a", null, (oldValue, value) -> oldValue + "-" + value); //NullPointerException, value 不能为 null

Map.Entry comparingByKey 和  comparingByValue 方法

另外介绍一下 Map.Entry 新加的两个排序方法,它们分别有无参与带 Comparator 参数可嵌套使用的两个版本。comparingByKey(), comparingByKey(Comparator<? super K> cmp), comparingByValue() 和 comparingByValue(Comparator<? super V> cmp)。

示例代码如下:

  1. map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
  2. map.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).collect(Collectors.toList());
  3. map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList());
  4. map.entrySet().stream().sorted(Map.Entry.comparingByValue(String::compareTo)).collect(Collectors.toList());

您可能感兴趣的文章:

文章同步发布: https://www.geek-share.com/detail/2755357127.html

Java8 Map中新增的方法使用总结的更多相关文章

  1. java代码之美(10)---Java8 Map中的computeIfAbsent方法

    Map中的computeIfAbsent方法 Map接口的实现类如HashMap,ConcurrentHashMap,HashTable等继承了此方法,通过此方法可以在特定需求下,让你的代码更加简洁. ...

  2. java代码(10) ---Java8 Map中的computeIfAbsent方法

    Map中的computeIfAbsent方法 一.案例说明 1.概述 在JAVA8的Map接口中,增加了一个computeIfAbsent,此方法签名如下: public V computeIfAbs ...

  3. Java8接口中的默认方法

    Java8新增特性,可以为接口中添加默认方法,实现这个接口的所有类都会继承这个方法,这样看起来,接口和类的界限就有点不明显了,同时也会带来多继承,菱形问题.这样设计的初衷是什么? 重所周知,java8 ...

  4. 带你学习ES5中新增的方法

    1. ES5中新增了一些方法,可以很方便的操作数组或者字符串,这些方法主要包括以下几个方面 数组方法 字符串方法 对象方法 2. 数组方法 迭代遍历方法:forEach().map().filter( ...

  5. Map中定义的方法:

    添加.删除.修改操作: Object put(Object key,Object value):将指定key-value添加到(或修改)当前map对象中void putAll(Map m):将m中的所 ...

  6. 谈谈map中的count方法

    map和set两种容器的底层结构都是红黑树,所以容器中不会出现相同的元素,因此count()的结果只能为0和1,可以以此来判断键值元素是否存在(当然也可以使用find()方法判断键值是否存在). 拿m ...

  7. map中的count方法

    map.count(Key)返回值为1或者0,1返回存在,0返回不存在,返回的是布尔类型的值,因为在map类型中所有的数据的Key值都是不同的,所以被count的数要么存在1次,要么不存在

  8. java 多种判断key是否在map中存在的方法

    java 中有时候会遇到判断传过来的map里是否包含了指定的key,我目前只发现两种办法,如果有其他方法欢迎补充 我添加上去: HashMap map = new HashMap(); map.put ...

  9. ES6中新增字符串方法,字符串模板

    多了两个新方法 startsWith endsWith 返回的是一个Boolean值 let str='git://www.baidu.com/2123123'; if(str.startsWith( ...

随机推荐

  1. SystemVerilog MCDF比较器

    checker肩负了模拟设计行为和功能检查任务. 功能: 缓存从各个monitor手机到的数据. ton过比较器检查实际收集到的DUT输出端口数据是否同reference module(参考模型)产生 ...

  2. Go语言流程控制03--goto跳转到任意标签位置

    package main import ( "fmt" "time" ) func main() { STUDYHARD: fmt.Println(" ...

  3. 构建编译TVM方法

    构建编译TVM方法 本文提供如何在各种系统上构建和安装TVM包的说明.它包括两个步骤: 1.     首先从C代码构建共享库( libtvm.so for linux, libtvm.dylib fo ...

  4. 目标检测中特征融合技术(YOLO v4)(下)

    目标检测中特征融合技术(YOLO v4)(下) ASFF:自适应特征融合方式 ASFF来自论文:<Learning Spatial Fusion for Single-Shot Object D ...

  5. 深度学习调用TensorFlow、PyTorch等框架

    深度学习调用TensorFlow.PyTorch等框架 一.开发目标目标 提供统一接口的库,它可以从C++和Python中的多个框架中运行深度学习模型.欧米诺使研究人员能够在自己选择的框架内轻松建立模 ...

  6. VB 老旧版本维护系列---尴尬的webapi访问返回json对象

    尴尬的webapi访问返回json对象 首先Imports Newtonsoft.Json Imports MSXML2(Interop.MSXML2.dll) Dim URLEncode As Sy ...

  7. Java期末考试编程题复习

    在程序中定义Person类,为该类编写如下字段.构造器.访问器.修改器和相应的其他方法.(20分) <1>在Person类中定义两个字段: 私有访问权限,类型为String的name字段: ...

  8. 【问题记录】—SignalR连接断线重连

    起因: ASP.NET Core SignalR是一个开源库,可简化向应用添加实时 SignalR Web 功能. 实时 Web 功能使服务器端代码能够立即将内容推送到客户端.(相信大家都用得比较多了 ...

  9. 错误:软件包:php-fpm-5.4.16-42.el7.x86_64 需要:php-common(x86-64)

    报错信息:错误:软件包:php-fpm-5.4.16-42.el7.x86_64 (/php-fpm-5.4.16-42.el7.x86_64)需要:php-common(x86-64) = 5.4. ...

  10. csp-s模拟测试49(9.22)养花(分块/主席树)·折射(神仙DP)·画作

    最近有点头晕........... T1 养花 考场我没想到正解,后来打的主席树,对于每个摸数查找1-(k-1),k-(2k-1)...的最大值,事实上还是很容易被卡的但是没有数据好像还比较友善, 对 ...