What is the proper way to remove elements from a scala mutable map using a predicate

蹲街弑〆低调 提交于 2020-01-22 13:27:52

问题


How to do that without creating any new collections? Is there something better than this?

val m = scala.collection.mutable.Map[String, Long]("1" -> 1, "2" -> 2, "3" -> 3, "4" -> 4)
m.foreach(t => if (t._2 % 2 == 0) m.remove(t._1))
println(m)

P.S. in Scala 2.8


回答1:


retain does what you want. In 2.7:

val a = collection.mutable.Map(1->"one",2->"two",3->"three")
a: scala.collection.mutable.Map[Int,java.lang.String] = 
  Map(2 -> two, 1 -> one, 3 -> three)

scala> a.retain((k,v) => v.length < 4)   

scala> a
res0: scala.collection.mutable.Map[Int,java.lang.String] =
  Map(2 -> two, 1 -> one)

It also works, but I think is still in flux, in 2.8.




回答2:


Per the Scala mutable map reference page, you can remove a single element with either -= or remove, like so:

val m = scala.collection.mutable.Map[String, Long]("1" -> 1, "2" -> 2, "3" -> 3, "4" -> 4)
m -= "1" // returns m
m.remove("2") // returns Some(2)

The difference is that -= returns the original map object, while remove returns an Option containing the value corresponding to the removed key (if there was one.)

Of course, as other answers indicate, if you want to remove many elements based on a condition, you should look into retain, filter, etc.




回答3:


If you are using an immutable.Map, in 2.7 it might have to be something like:

def pred(k: Int, v: String) = k % 2 == 0

m --= (m.filter(pred(_, _)).keys

As there is no retain method available. Obviously in this case m must be declared as a var



来源:https://stackoverflow.com/questions/2500548/what-is-the-proper-way-to-remove-elements-from-a-scala-mutable-map-using-a-predi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!