使用谓词从 scala 可变映射中删除元素的正确方法是什么
如何在不创建任何新集合的情况下做到这一点?还有比这更好的事情吗?
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)
Scala 2.8 中的 PS
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
retain
做你想要的。在 2.7 中:它也有效,但我认为在 2.8 中仍在不断变化。
retain
does what you want. In 2.7:It also works, but I think is still in flux, in 2.8.
根据 Scala 可变映射参考页面,您可以使用 -= 或remove 删除单个元素,如下所示:
区别在于 -= 返回原始映射对象,而remove 返回一个 Option,其中包含与删除的键对应的值(如果有的话)。
当然,正如其他答案所示,如果您想根据条件删除许多元素,您应该考虑保留、过滤等。
Per the Scala mutable map reference page, you can remove a single element with either -= or remove, like so:
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.
如果您使用
immutable.Map
,在 2.7 中,它可能必须类似于:因为没有可用的
retain
方法。显然在这种情况下m
必须声明为var
If you are using an
immutable.Map
, in 2.7 it might have to be something like:As there is no
retain
method available. Obviously in this casem
must be declared as avar
对于 scala version=2.13.6 使用 filterInPlace
文档链接
for scala version=2.13.6 use filterInPlace
doc link