Get value of nested maps in Scala

谁说我不能喝 提交于 2019-12-11 02:16:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!