user866364
user866364

Reputation:

Functional way to update a Map

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

Answers (4)

AbuNassar
AbuNassar

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

user7938511
user7938511

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

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25909

val updatedScore = score -> (currentScores(score)+ 1)
val newScores= currentScores - score + newScore

Upvotes: 0

nmat
nmat

Reputation: 7591

You can do it like this:

val newScores = currentScores + (score -> (currentScores.getOrElse(score, 0) + 1))

Upvotes: 7

Related Questions