在Scala中获取嵌套地图的价值 [英] Get value of nested maps in Scala
本文介绍了在Scala中获取嵌套地图的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有以下结构的地图:
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?
推荐答案
只需按常规方法进行两次即可.
Just do it the normal way... twice.
val m = Map("a" -> Map("b" -> "c"))
m("a")("b") // c
第一个操作m("a")
返回内部的Map[String,String]
.第二个操作that("b")
返回返回的Map内的String.
The first operation m("a")
returns the inner Map[String,String]
. The second operation that("b")
returns the String inside of that returned Map.
与以下相同:
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
对于您的示例,key2
是Option
,就像m.get(key1)
一样,因此您可以用相同的方式处理它:
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)
这篇关于在Scala中获取嵌套地图的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文