0

I have an Array of Tuple2 that contains a String and a map, and I'd like to print for each tuple2 as many rows as the number of keys of the map. This is what I wrote:

val a = Array(
           ("foo", HashMap(1->"f1", 2->"f2")),
           ("bar", HashMap(1->"b1", 2->"b2"))
        )

for (sourceNode <- a) {
   for (destNode <- sourceNode._2) {
     println("value [" + sourceNode._1 + "] for [" + destNode._1 + "] is '" + destNode._2 + "'")
   }
 }

and here is the result:

value [foo] for [1] is 'f1'
value [foo] for [2] is 'f2'
value [bar] for [1] is 'b1'
value [bar] for [2] is 'b2'

The result is correct, but is there a more concise (and functional) way to obtain this result?

Thanks, Andrea

2
  • What you have is functional ... I am not sure you can get something "more functional" that that. Commented Nov 7, 2015 at 17:16
  • @marios what I meant with functional is using map() or flatMap() or something similar.. Commented Nov 7, 2015 at 18:15

3 Answers 3

1

I think the OP is looking for a solution using map and flatMap (instead of the syntactic sugar of for-comprehensions).

Here is one attempt to do that. First you decompose the (key,Map) pair into (key1,key2,value) tuple and then you just provide a print method. Here is the code:

val a = Array(
           ("foo", Map(1->"f1", 2->"f2")),
           ("bar", Map(1->"b1", 2->"b2"))
        )

a.flatMap{
   case(k,theMap) => theMap.map(e => (k,e._1,e._2))
}.foreach{ case(k1,k2,v) => println(s"value [$k1] for [$k2] is '$v'") }
Sign up to request clarification or add additional context in comments.

Comments

1

You could do this

for ((name, map) <- a) {
  for ((key, value) <- map) {
    println("value [" + name + "] for [" + key + "] is '" + value + "'")
  }
}

But you can make it even more concise

for {
  (name, map) <- a
  (key, value) <- map
} println(s"value [$name] for [$key] is '$value'")

Here is some more information on for comprehensions http://docs.scala-lang.org/tutorials/tour/sequence-comprehensions.html

Comments

1

Similar to your solution with foreach

a foreach { t => 
    t._2 foreach { m =>
      println("value [" + t._1 + "] for [" + m._1 + "] is '" + m._2 + "'")
    }
}

Comments

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.