scala 如何从scala中的地图中删除键值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21955560/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:05:09  来源:igfitidea点击:

how to remove key value from map in scala

scaladictionarycollectionsplayframeworkscala-collections

提问by Govind Singh

Map(data -> "sumi", rel -> 2, privacy -> 0, status -> 1,name->"govind singh")

how to remove data from this map , if privacy is 0.

如果隐私为 0,如何从此地图中删除数据。

Map(rel -> 2, privacy -> 0, status -> 1,name->"govind singh")  

回答by Leo

If you use immutable maps, you can use the -method to create a new map without the given key:

如果使用不可变映射,则可以使用该-方法在没有给定键的情况下创建新映射:

val mx = Map("data" -> "sumi", "rel" -> 2, "privacy" -> 0)

val m = mx("privacy") match {
    case 0 => mx - "data"
    case _ => mx
}

=> m: scala.collection.immutable.Map[String,Any] = Map(rel -> 2, privacy -> 0)

If you use mutable maps, you can just remove a key with either -=or remove.

如果您使用可变映射,则可以使用-=或删除键remove

回答by Kevin Wright

If you're looking to scale this up and remove multiple members, then filterKeysis your best bet:

如果您希望扩大规模并删除多个成员,那么filterKeys您最好的选择是:

val a = Map(
  "data"    -> "sumi",
  "rel"     -> "2",
  "privacy" -> "0",
  "status"  -> "1",
  "name"    -> "govind singh"
)

val b = a.filterKeys(_ != "data")

回答by Sudeep Juvekar

That depends on the type of Scala.collection Map you are using. Scala comes with both mutableand immutableMaps. Checks these links:

这取决于您使用的 Scala.collection Map 类型。Scala 带有mutableimmutableMaps。检查这些链接:

http://www.scala-lang.org/api/2.10.2/index.html#scala.collection.immutable.Map

http://www.scala-lang.org/api/2.10.2/index.html#scala.collection.immutable.Map

and

http://www.scala-lang.org/api/2.10.2/index.html#scala.collection.mutable.Map

http://www.scala-lang.org/api/2.10.2/index.html#scala.collection.mutable.Map

In both types of maps, -is usually the operation to remove a key. The details depend on the type of map. A mutablemap can be modified in place by using -=. Something like

在这两种类型的映射中,-通常是删除一个键的操作。详细信息取决于地图类型。甲mutable地图来代替通过使用进行修改-=。就像是

if (m.contains("privacy") && m.getOrElse("privacy", 1) == 0) {
    m -= "play"
}

On the other hand, an immutable map can not be modified in place and has to return a new map after removing an element.

另一方面,不可变映射不能就地修改,必须在删除元素后返回新映射。

if (m.contains("privacy") && m.getOrElse("privacy", 1) == 0) {
    val newM = m - "play"
}

Notice that you are creating a new immutable map.

请注意,您正在创建一个新的不可变映射。

回答by RAGHHURAAMM

val m = Map("data" -> "sumi", "rel" -> 2, "privacy" -> 0,"status" -> 1,"name"->"govind singh")
scala> if(m("privacy")==0) m.filterKeys(_ != "data")
res63: Any = Map(name -> govind singh, rel -> 2, privacy -> 0, status -> 1)