java8map的方法_java8 map - 新特性常用方法

前言

java8中对map的使用新增了一些十分有用的方法,以下列举部分常用methed()

常用方法解析

1、compute()

参数格式:

compute(K key,BiFunction super K, ? super V, ? extends V> remappingFunction)

简要说明:

不在乎当前item的旧值,直接以remappingFunction()结果的新值为准,如果新值为空则移除当前item.

源码分析:

default V compute(K key,

BiFunction super K, ? super V, ? extends V> remappingFunction) {

Objects.requireNonNull(remappingFunction);

V oldValue = get(key);

V newValue = remappingFunction.apply(key, oldValue);

if (newValue == null) {

// delete mapping

if (oldValue != null || containsKey(key)) {

// something to remove

remove(key);

return null;

} else {

// nothing to do. Leave things as they were.

return null;

}

} else {

// add or replace old mapping

put(key, newValue);

return newValue;

}

使用格式:

testMap.compute("key1", (v1, v2) -> v2);

使用场景:

put()方法的增强使用

2、computeIfPresent()

参数格式:

computeIfPresent(K key, BiFunction super K, ? super V, ? extends V> remappingFunction)

简要说明:

计算item方法, 入参为item的key、remappingFunction

如果原来的key有值,且不为null,那么将remappingFunction中的新值给key,新值如果为空,移除当前key的item

如果原来key没值,直接给null

源码分析:

default V computeIfPresent(K key,

BiFunction super K, ? super V, ? extends V> remappingFunction) {

Objects.requireNonNull(remappingFunction);

V oldValue;

if ((oldValue = get(key)) != null) {

V newValue = remappingFunction.apply(key, oldValue);

if (newValue != null) {

put(key, newValue);

return newValue;

} else {

remove(key);

return null;

}

} else {

return null;

}

使用格式:

testMap.computeIfPresent("key1", (v1, v2) -> "test");

使用场景:

put()方法的增强使用

3、computeIfAbsent()

参数格式: computeIfAbsent(K key, Function super K, ? extends V> mappingFunction)

简要说明:

计算item方法,入参为item的key、remappingFunction

如果当前key旧值不为空,那么以旧值为准

如果当前key旧值为空,以function结果新值为准,新值为空则remove当前item

源码分析:

default V computeIfAbsent(K key,

Function super K, ? extends V> mappingFunction) {

Objects.requireNonNull(mappingFunction);

V v;

if ((v = get(key)) == null) {

V newValue;

if ((newValue = mappingFunction.apply(key)) != null) {

put(key, newValue);

return newValue;

}

}

return v;

}

使用格式:

tempEntityRouteMap.computeIfAbsent(entityType, k -> TreeRangeMap.create());

使用场景:

put()方法的增强使用

未完待续......

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值