[英]Add key-value pair to a HashMap with an existing key (Scala)
I have a following HashMap 我有以下HashMap
import collection.mutable.HashMap
val map = mutable.HashMap("key" -> mutable.HashMap("key" -> "value",
"key2" -> "value2"),
"key2" -> mutable.HashMap("key" -> "value",
"key2" -> "value2"))
How can I get the map look like 我怎样才能使地图看起来像
val map = mutable.HashMap("key" -> mutable.HashMap("key" -> "value",
"key2" -> "value2"),
"key2" -> mutable.HashMap("key" -> "value",
"key2" -> "value2",
"key3" -> "value3"),
"key3" -> mutable.HashMap("key" -> "value"))
In my head it would go something like this but I could not find a correct way. 在我的脑海中会出现类似这样的情况,但是我找不到正确的方法。
map.get("key2").put("key3" -> "value3")
map.put("key3" -> ("key" -> "value3"))
Ultimately I want a structure which is easy to convert to Json 最终,我想要一个易于转换为Json的结构
The put
method does not work with parameters in the form of key -> value
. put
方法不适用于key- key -> value
形式的参数。 You have to use +
-operator. 您必须使用
+
-operator。 Also .get(key)
returns an Option
, so you have to .map
on it: 此外,
.get(key)
返回一个Option
,因此您必须对其进行.map
:
map.get("key2").map(_ + "key3" -> "value3")
map += ("key3" -> mutable.HashMap("key" -> "value3"))
Also in the second line you need to explicitly create a HashMap otherwise it won't match the type of the map ( [String, HashMap]
). 同样在第二行中,您需要显式创建一个HashMap,否则它将与地图的类型(
[String, HashMap]
)不匹配。
This should answer you question, but Yuval Itzchakov is right, it might prove a good idea to use case classes and JSON serializer such as Jackson or Json4s , if you have a fixed structure for your objects. 这应该可以回答您的问题,但是Yuval Itzchakov是正确的,如果您的对象具有固定的结构,那么使用案例类和JSON序列化程序(例如Jackson或Json4s)可能是一个好主意。
You cannot use 你不能使用
map.get("key2").put("key3" -> "value3")
because it returns Option
and it expects two parameters, not a tuple. 因为它返回
Option
并且需要两个参数,而不是元组。 You would need to unwrap value first by calling get
and then call it like this: 您首先需要通过调用
get
来解开值,然后像这样调用它:
map.get("key2").get.put("key3", "value3")
But there are simpler way to add new values to mutable map: 但是,有更简单的方法可以向可变映射添加新值:
map("key3") = mutable.HashMap("key" -> "value", "key2" -> "value2")
map("key2")("key3") = "value3"
// or
map += ("key3" -> mutable.HashMap("key" -> "value", "key2" -> "value2"))
map("key2") += ("key3" -> "value3")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.