更新地图的功能方式

pla*_*oom 2 scala

我想检查Map中是否存在键,如果存在,我想在值上增加1.如果不存在,我想在Map上放一个新项目,其值等于1.

什么是'功能方式'来做到这一点?我用find和fold写了它,但它看起来有点奇怪.

val updatedScore = currentScores
  .find(s => s._1.equals(score))
  .fold(score -> 1)(s => s._1 -> (s._2 + 1))

val newScores = currentScores + updatedScore
Run Code Online (Sandbox Code Playgroud)

任何人都有更好的解决方案来做同样的事情?

nma*_*mat 8

你可以这样做:

val newScores = currentScores + (score -> (currentScores.getOrElse(score, 0) + 1))
Run Code Online (Sandbox Code Playgroud)