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

时间:2010-10-22 03:09:22

标签: scala map add mutable put

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

以下是一些失败的尝试:

val map = scala.collection.mutable.Map

map("mykey") = "myval"

map += "mykey" -> "myval"

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

7 个答案:

答案 0 :(得分:81)

关键是您的代码的第一行不是您所期望的。

您应该使用:

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)

答案 1 :(得分:43)

与往常一样,你应该质疑你是否真的需要一张可变的地图。

不可变的地图构建起来很简单:

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

首次构建时,可变映射没有区别:

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

map += "nextkey" -> "nextval"

在这两种情况下,推理都将用于确定Map实例的正确类型参数。

您还可以在var中保存不可变地图,每次执行“更新”时,变量将使用新的不可变地图实例进行更新

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

答案 2 :(得分:16)

当你说

val map = scala.collection.mutable.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))

答案 3 :(得分:2)

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

答案 4 :(得分:2)

创建一个新的不可变地图:

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

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

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

答案 5 :(得分:2)

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

scala> var d= collection.mutable.Map[Any, Any]()
d: scala.collection.mutable.Map[Any,Any] = 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"

检查更新后的地图:

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

答案 6 :(得分:0)

var map:Map [String,String] = Map()

var map1 = map +(“ red”->“#FF0000”)

println(map1)