使用谓词从 Scala 可变映射中删除元素的正确方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2500548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the proper way to remove elements from a scala mutable map using a predicate
提问by Oleg Galako
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
Scala 2.8 中的 PS
回答by Rex Kerr
retaindoes what you want. In 2.7:
retain做你想做的。在 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.8 中仍在不断变化。
回答by Jonathan Stray
Per the Scala mutable map reference page, you can remove a single element with either -= or remove, like so:
根据 Scala mutable map reference page,您可以使用 -= 或 remove 删除单个元素,如下所示:
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.)
不同之处在于 -= 返回原始地图对象,而 remove 返回一个包含与删除的键对应的值的选项(如果有的话)。
Of course, as other answers indicate, if you want to remove many elements based on a condition, you should look into retain, filter, etc.
当然,正如其他答案所指出的,如果您想根据条件删除许多元素,您应该查看保留、过滤器等。
回答by oxbow_lakes
If you are using an immutable.Map, in 2.7it might have to be something like:
如果您使用的是immutable.Map,则在2.7 中它可能必须是这样的:
def pred(k: Int, v: String) = k % 2 == 0
m --= (m.filter(pred(_, _)).keys
As there is no retainmethod available. Obviously in this case mmust be declared as a var
因为没有retain可用的方法。显然在这种情况下m必须声明为var

