前言

得益于 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 值。

参考实现:

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

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

示例及效果:

String ret;
Map<String, String> map = new HashMap<>();
ret = map.putIfAbsent("a", "aaa"); //ret 为"aaa", map 为 {"a":"aaa"}
ret = map.putIfAbsent("a", "bbb"); //ret 为 "aaa", map 还是 {"a":"aaa"}map.put("b", null);
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)。

参考实现:

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);
}

示例及效果:

String ret;
Map<String, String> map = new HashMap<>();
ret = map.computeIfPresent("a", (key, value) -> key + value); //ret null, map 为 {}
map.put("a", null); //map 为 ["a":null]
ret = map.computeIfPresent("a", (key, value) -> key + value); //ret null, map 为 {"a":null}
map.put("a", "+aaa");
ret = map.computeIfPresent("a", (key, value) -> key + value); //ret "a+aaa", map 为 {"a":"a+aaa"}
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)。

参考实现:

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

示例及效果:

String ret;
Map<String, String> map = new HashMap<>();
ret = map.computeIfAbsent("a", key -> key + "123"); //ret "a123", map 为 {"a":"a123"}
ret = map.computeIfAbsent("a", key -> key + "456"); //ret "a123", map 为 {"a":"a123"}
map.put("a", null);
ret = map.computeIfAbsent("a", key -> key + "456"); //ret "a456", map 为 {"a":"a456"}
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) 值。

参考实现:

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

示例及效果:

String ret;
Map<String, String> map = new HashMap<>();
ret = map.replace("a", "abc"); //ret 为 null,map 为 {}
map.put("a", "ddd");
ret = map.replace("a", "abc"); //ret 为 "ddd", map 为 {"a":"abc"}
ret = map.replace("a", null); //ret 为 "abc", map 为 {"a":null}
ret = map.replace("a", "ddd"); //ret 为 null, map 为 {"a":"ddd"}

replace(K key, V oldValue, V newValue)

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

参考实现:

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

示例及效果:

boolean ret;
Map<String, String> map = new HashMap<>() ;
ret = map.replace("a", null, "aaa"); //ret 为 false, map 为 {}
map.put("a", null);
ret = map.replace("a", null, "aaa"); //ret 为 true, map 为 {"a":"aaa"}
ret = map.replace("a", "aaa", null); //ret 为 true, map 为 {"a":null}
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。

参考实现:

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

示例及效果:

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

remove(key, value)

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

参考实现:

if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
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)。

参考实现:

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;
}

示例及效果:

String ret;
Map<String, String> map = new HashMap<>() ;
ret = map.compute("a", (key, value) -> "a" + value); //ret="anull", map={"a":"anull"}
ret = map.compute("a", (key, value) -> "a" + value); //ret="aanull", map={"a":"aanull"}
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) 值。

参考实现:

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);

注意 value 不能为 null 值

示例及效果:

String ret;
Map<String, String> map = new HashMap<>() ;
ret = map.merge("a", "aa", (oldValue, value) -> oldValue + "-" + value); //ret="aa", map={"a":"aa"}
ret = map.merge("a", "bb", (oldValue, value) -> oldValue + "-" + value); //ret="aa-bb", map={"a":"aa-bb"}
ret = map.merge("a", "bb", (oldValue, value) -> null); //ret=null, map={}
map.put("a", null);
ret = map.merge("a", "aa", (oldValue, value) -> oldValue + "-" + value); //ret="aa", map={"a":"aa"}
map.put("a", null);
ret = map.merge("a", "bb", (oldValue, value) -> null); //ret="bb", map={"a":"bb"}
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)。

示例代码如下:

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

您可能感兴趣的文章:

  • 浅谈java8中map的新方法--replace

  • Java8中利用stream对map集合进行过滤的方法

  • Java8 HashMap的实现原理分析

  • 在Java8与Java7中HashMap源码实现的对比

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

转载于:https://www.cnblogs.com/sohuhome/p/10094772.html

Java8 Map中新增的方法使用总结相关推荐

  1. Java8 Map 中新增的方法使用记录

    得益于 Java 8的 default方法特性,Java 8对 Map增加了不少实用的默认方法,像getOrDefault,forEach,replace,replaceAll,putIfAbsent ...

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

    ES6中新增字符串方法,字符串模板 多了两个新方法 startsWith endsWith 返回的是一个Boolean值 let str='git://www.baidu.com/2123123';i ...

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

    文章目录 1. ES5中新增了一些方法,可以很方便的操作数组或者字符串,这些方法主要包括以下几个方面 2. 数组方法 2.1 forEach跟jQuery的each用法类似.语法是: 2.2 map( ...

  4. Map中的keySet方法

    有一个Map对象,这时候使用keySet()方法获取所有的key值,比如:    Map map = new HashMap();    map.put(1, "a");    m ...

  5. Java8 Stream 中的 reduce() 方法,执行聚合操作

    初识 Stream 中的 reduce() 方法,是在最近一次刷算法题的过程中(下面会讲到),简洁干练的写法,让我眼前一亮. 所以,我简单学习了,总结了一下写法: 正文 Java 8 API添加了一个 ...

  6. 36 ES5中新增的方法

    技术交流QQ群:1027579432,欢迎你的加入! 欢迎关注我的微信公众号:CurryCoder的程序人生 1.ES5新增方法概述 ES5中给我们新增了一些方法,可以很方便的操作数组或字符串,这些方 ...

  7. Map中的putAll方法

    HashMap map1=new HashMap();         HashMap map2 = new HashMap(); map2.putAll(map1) 上面的代码的意思是将map1中所 ...

  8. java8 Map新增方法的使用

    文章目录 文章目录 文章目录 java8 Map新增方法的使用 概述 1.compute() 1.使用 2.源码实现 2.computeIfAbsent() 1.使用 2.源码 3.computeIf ...

  9. ES6/02/创建对象,构造函数和原型,原型和原型链,this指向,类,ES5新增的方法,数组方法,回调函数,ES5新增的字符串方法,ES5中新增的对象方法

    创建对象 1,利用new Object()创建对象 var obj1 =new Object(); 2,利用对象字面量创建对象 var obj2={}; 3,利用构造函数创建对象 function S ...

最新文章

  1. 矩阵连乘算法代码JAVA_矩阵连乘问题的动态规划算法(java)
  2. java排序的几种方法
  3. 全球及中国晶圆键合和解键合设备行业竞争格局分析及投资前景评估报告2021年版
  4. 当12C PDB遇上JDBC
  5. 第四冠!腾讯AI「绝艺」斩获世界智能围棋公开赛冠军
  6. 真实HDFS集群启动后master的jps没有DataNode
  7. android 手机自动化测试,Appium进行Android手机真机自动化测试
  8. 4 年 46 个版本,一文读懂 Spring Cloud 发展历史
  9. Linux7/Redhat7/Centos7 安装Oracle 12C_配置VNC远程安装数据库_03
  10. 每日一乐,健康多滋味~~
  11. zabbix 2.2 监控mysql_zabbix2.2入门教程之监控mysql(六)
  12. java获取汉字的拼音首字母_java获取汉字的拼音首字母
  13. VC2010 编译 Media Player Classic - Home Cinema (mpc-hc)
  14. 怎样卸载连接老师的计算机软件,我的电脑里面solidworks无法卸载,,老师能帮我下吗...
  15. day 05 字典dic(增删改查 嵌套)
  16. STL中vector介绍
  17. SQL LIKE通配符 模糊查询
  18. Js学习之拖拉事件(drag)
  19. 谷歌创始人年度公开信:搜索仍是谷歌的核心
  20. OSGearth学习(一)

热门文章

  1. Eclipse Modeling Framework, 2nd Edition. (EMF)学习笔记(一)——EMF介绍
  2. PHP课程20161114
  3. “笨方法”学习Python笔记(1)-Windows下的准备
  4. 利用命令清除和设定静态IP地址
  5. windows mobile开发循序渐进(5)移动应用程序与webservice之间的数据交互
  6. 不是VIP用户也不怕 不需任何补丁屏蔽迅雷广告!
  7. NIO网络编程实战之简单多人聊天室
  8. 2010年9月14日佛山大沥机楼网络故障日志
  9. 2008年10月10日股票池
  10. currentThread的一个复杂案例