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

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

为达到熟练运用上述除getOrDefaultforEach外的其他方法,有必要逐一体验一番,如何调用,返回值以及调用后的效果如何。看看每个方法不至于 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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VBxkdjL4-1650335196489)(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1541065234273&di=148413bc0cf12cfad45cafa9e0efd541&imgtype=0&src=http%3A%2F%2Fwww.itjiaocheng.com%2Fuploads%2Fuserup%2F469%2F1504774642.jpg)]

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),它是computeIfAbsentcomputeIfPresent 的结合体。也就是既不管 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());

;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值