向scala.collection.mutable.Map添加元素的语法是什么?

0md85ypi  于 2022-12-29  发布在  Scala
关注(0)|答案(7)|浏览(170)

scala.collection.mutable.Map添加元素的语法是什么?
以下是一些失败的尝试:

val map = scala.collection.mutable.Map

map("mykey") = "myval"

map += "mykey" -> "myval"

map.put("mykey","myval")
jutyujz0

jutyujz01#

关键是代码的第一行不是您所期望的。
您应该用途:

val map = scala.collection.mutable.Map[A,B]()

然后,您可以使用多个等效替代项来添加项目:

scala> val map = scala.collection.mutable.Map[String,String]()
map: scala.collection.mutable.Map[String,String] = Map()

scala> map("k1") = "v1"

scala> map
res1: scala.collection.mutable.Map[String,String] = Map((k1,v1))

scala> map += "k2" -> "v2"
res2: map.type = Map((k1,v1), (k2,v2))

scala> map.put("k3", "v3")
res3: Option[String] = None

scala> map
res4: scala.collection.mutable.Map[String,String] = Map((k3,v3), (k1,v1), (k2,v2))

Scala 2.13开始:

scala> map.addOne("k4" -> "v4")
res5: map.type = HashMap(k1 -> v1, k2 -> v2, k3 -> v3, k4 -> v4)
mw3dktmi

mw3dktmi2#

和往常一样,您应该问自己是否真的需要可变Map。
构建不可变Map很简单:

val map = Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

可变Map在第一次构建时没有什么不同:

val map = collection.mutable.Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

map += "nextkey" -> "nextval"

在这两种情况下,都将使用推理来确定Map示例的正确类型参数。
您也可以在var中保存一个不可变Map,然后在每次执行“更新”时,都会用新的不可变Map示例更新该变量

var map = Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

map += "nextkey" -> "nextval"

如果没有任何初始值,可以使用Map.empty:

val map : Map[String, String] = Map.empty //immutable
val map = Map.empty[String,String] //immutable
val map = collection.mutable.Map.empty[String,String] //mutable
mhd8tkvw

mhd8tkvw3#

当你说

val map = scala.collection.mutable.Map

您不是在创建贴图示例,而是在创建Map类型的别名。

map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e

请尝试以下操作:

scala> val map = scala.collection.mutable.Map[String, Int]()
map: scala.collection.mutable.Map[String,Int] = Map()

scala> map("asdf") = 9

scala> map
res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9))
mi7gmzs6

mi7gmzs64#

创建新的不可变Map:

scala> val m1 = Map("k0" -> "v0")   
m1: scala.collection.immutable.Map[String,String] = Map(k0 -> v0)

向上面的map添加一个新的键/值对(并创建一个新的map,因为它们都是不可变的):

scala> val m2 = m1 + ("k1" -> "v1")             
m2: scala.collection.immutable.Map[String,String] = Map(k0 -> v0, k1 -> v1)
wvt8vs2t

wvt8vs2t5#

var test = scala.collection.mutable.Map.empty[String, String]
test("myKey") = "myValue"
1rhkuytd

1rhkuytd6#

创建一个没有初始值的可变Map:

scala> var d= collection.mutable.Map[Any, Any]()
d: scala.collection.mutable.Map[Any,Any] = Map()

使用初始值创建可变Map:

scala> var d= collection.mutable.Map[Any, Any]("a"->3,1->234,2->"test")
d: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, a -> 3, 1 -> 234)

更新现有键值:

scala> d("a")= "ABC"

添加新键值:

scala> d(100)= "new element"

检查更新的Map:

scala> d
res123: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, 100 -> new element, a -> ABC, 1 -> 234)
r1zk6ea1

r1zk6ea17#

变量Map:Map[字符串,字符串] = Map()
变量Map1 =Map+(“红色”-〉“#FF0000”)
打印输入(Map1)

相关问题