Remove keys from a mutable map

What is idiomatic way to iterate through a mutable map and remove key with zero values?

I came up with this

// Prepare
import scala.collection.mutable.HashMap
val register = HashMap.empty[String, Int]
register += "A" ->1
register += "B" ->0

//Remove if value is zero
register.foreach(i => if (i._2==0) register -= i._1)

but it still looks awkward and not functional enough to me. I feel that in really functional approach we should mention register only once. Compare with Mathematica code

register = {{"A", 1}, {"B", 0}};
DeleteCases[register, {_, 0}]

The moment you have a mutable map you are a little far away from functional programming.
Anyways, as I always say, the Scaladoc is your friend, you can just use filterInPlace

register.filterInPlace {
  case (_, value) =>
    value == 0
}
1 Like

@BalmungSan Actually your code does just opposite: it keeps exclusively the elements that need to be removed. But it is easy to fix

register.filterInPlace {
  case (_, value) =>
    value != 0
}
1 Like