Reputation:
I would like to check if a key exists inside a Map and if exists, i would like to increment 1 on value. If not exists, I would like to put a new item on Map with value equals 1.
What's the 'functional way' to do it? I've wrote it using find and fold but it's look kinda strange.
val updatedScore = currentScores
.find(s => s._1.equals(score))
.fold(score -> 1)(s => s._1 -> (s._2 + 1))
val newScores = currentScores + updatedScore
Anyone have a better solution to do the same?
Upvotes: 2
Views: 461
Reputation: 1225
If your goal is to count, consider using a MultiMap, i.e.: http://lampwww.epfl.ch/~hmiller/scaladoc/library/scala/collection/mutable/MultiMap.html. Since you're accumulating counts, there doesn't seem to be a good reason to avoid side effects.
Upvotes: 0
Reputation: 167
val ret: mutable.Map[Int, Int] = mutable.Map[Int, Int]().withDefaultValue(1)
val arg = 5
ret.update(arg, ret(5)+1)
Upvotes: 1
Reputation: 25909
val updatedScore = score -> (currentScores(score)+ 1)
val newScores= currentScores - score + newScore
Upvotes: 0
Reputation: 7591
You can do it like this:
val newScores = currentScores + (score -> (currentScores.getOrElse(score, 0) + 1))
Upvotes: 7