Reputation: 802
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
Upvotes: 0
Views: 2461
Reputation: 8996
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'") }
Upvotes: 1
Reputation: 4347
Similar to your solution with foreach
a foreach { t =>
t._2 foreach { m =>
println("value [" + t._1 + "] for [" + m._1 + "] is '" + m._2 + "'")
}
}
Upvotes: 1
Reputation: 8139
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
Upvotes: 1