使用谓词从scala可变映射中删除元素的正确方法是什么 [英] What is the proper way to remove elements from a scala mutable map using a predicate
本文介绍了使用谓词从scala可变映射中删除元素的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不创建任何新集合的情况下做到这一点?有什么比这更好的吗?
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.在Scala 2.8中
P.S. in Scala 2.8
推荐答案
retain
做您想要的.在2.7版中:
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)
它也可以工作,但我认为它在2.8中仍在不断发展.
It also works, but I think is still in flux, in 2.8.
这篇关于使用谓词从scala可变映射中删除元素的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文