Scala HashMap getOrElse 与 getOrElseUpdate

使用Map的过程中,发现有和 getOrElse 相似的方法 getOrElseUpdate ,大概看下具体是在做什么~


getOrElse

getOrElse经常用到,当 HashMap 获取某个不存在的key时会返回一个default默认值,从而避免出现 null point 的情况

/** Returns the value from this `Success` or the given `default` argument if this is a `Failure`.
 *
 * ''Note:'': This will throw an exception if it is not a success and default throws an exception.
 */
def getOrElse[U >: T](default: => U): U =
  if (isSuccess) get else default

getOrElseUpdate

getOrElseUpdate 其实是 getOrElse的升级版,当获取不存在的key时,不再返回默认值 default,而是根据 op 这个方法根据当前获取的不存在的key返回一个value,并将这个 key-value 存入 HashMap,这也就是 update 的由来

/** If given key is already in this map, returns associated value.
 *
 *  Otherwise, computes value from given expression `op`, stores with key
 *  in map and returns that value.
 *
 *  Concurrent map implementations may evaluate the expression `op`
 *  multiple times, or may evaluate `op` without inserting the result.
 *  
 *  @param  key the key to test
 *  @param  op  the computation yielding the value to associate with `key`, if
 *              `key` is previously unbound.
 *  @return     the value associated with key (either previously or as a result
 *              of executing the method).
 */
def getOrElseUpdate(key: A, op: => B): B =
  get(key) match {
    case Some(v) => v
    case None => val d = op; this(key) = d; d
  }

Test ⤵️

val testHashMap = mutable.HashMap[String,Int]()

# 定义 update 规则
def op(num: String) :Int = Try(num.toInt).getOrElse(0) * 2
def update(s: String): Int = testHashMap.getOrElseUpdate(num,op(num))

# key "1" 存在 key "2" 不存在 
testHashMap("1") = 1
val value_1 = update("1")
val value_2 = update("2")
    
# 检查执行结果
println(value_1,value_1)
println(testHashMap)
(1,4)
Map(2 -> 4, 1 -> 1)
07-30 115
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BIT_666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值