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

后端 未结 3 984
梦毁少年i
梦毁少年i 2021-02-13 06:29

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\"         


        
3条回答
  •  执念已碎
    2021-02-13 07:16

    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.

提交回复
热议问题