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

后端 未结 3 986
梦毁少年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:29

    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.

提交回复
热议问题