JereK
JereK

Reputation: 83

Add key-value pair to a HashMap with an existing key (Scala)

I have a following 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

Upvotes: 0

Views: 1780

Answers (2)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22635

You cannot use

map.get("key2").put("key3" -> "value3")

because it returns Option and it expects two parameters, not a tuple. You would need to unwrap value first by calling get and then call it like this:

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")

Upvotes: 2

thwiegan
thwiegan

Reputation: 2173

The put method does not work with parameters in the form of key -> value. You have to use +-operator. Also .get(key) returns an Option, so you have to .map on it:

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]).

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.

Upvotes: 2

Related Questions