问题
I have a map with the following structure:
Map[String, Map[String, String]]
Is there an elegant way of getting the value of the inner map?
回答1:
Just do it the normal way... twice.
val m = Map("a" -> Map("b" -> "c"))
m("a")("b") // c
The first operation m("a")
returns the inner Map[String,String]
. The second operation that("b")
returns the String inside of that returned Map.
It's the same as:
val m = Map("a" -> Map("b" -> "c"))
val m2 = m("a") // Map(b -> c)
m2("b") // c
On the other hand, if you think that they keys may not be there, then do this:
for {
x <- m.get("a") // x = Map(b -> c)
y <- x.get("b") // y = c
} yield y
// Some(c)
for {
x <- m.get("a") // x = Map(b -> c)
y <- x.get("d") // fails
} yield y
// None
for {
x <- m.get("c") // fails
y <- x.get("d") // doesn't run
} yield y
// None
For your example, key2
is an Option
, just like m.get(key1)
, so you can handle it the same way:
val key1: String = "a"
val key2: Option[String] = Some("b")
for {
value1 <- m.get(key1)
k2 <- key2
value2 <- value1.get(k2)
} yield value2
// Some(c)
来源:https://stackoverflow.com/questions/28998429/get-value-of-nested-maps-in-scala