3

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 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer. In the "for" section, suppose I need to get the value of the second map ("b" is used in the example) from a var that is defined as Option[String]. Is there a neat way of doing it?
Some(1).flatMap(Map(1 -> 2).get) - where Some(1) is your lookup key
Sorry, I didn't get it... Here is my code: def getValue(key1: String, key2: Option[String]): Option[String] = { for { value1 <- myMap.get(key1) value2 <- value1.get(key2) } yield Of course, this part will not work: value1.get(key2), since key2 is an option.
I had to use DerivedFeaturesLocations("outer_key").asInstanceOf[Map[String, String]]("inner_key"). Why is that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.