byomjan
byomjan

Reputation: 119

Scala using two maps to get the third map

Using scala 2.12 , joining the value of map1 with key of map2 to get the value of map2 Not sure how to achieve. Please help

val t1=Map("K1"->"tempV1" , "K2"->"tempV2" , "K3"-> "tempV3","K4"->"tempV4")
val t2=Map("tempV1"->"V1" , "tempV2"->"V2" , "tempV3"-> "V3","someV4"->"V4")



//expected  
Map("K1"->"V1","K2"->"V2","K3"->"V3")

Upvotes: 1

Views: 63

Answers (2)

jwvh
jwvh

Reputation: 51271

t1.flatMap{case (k,v) => t2.get(v).map(k -> _)}

Or, the equivalent expression:

for {
  (k,v1) <- t1
  v2     <- t2.get(v1)
} yield (k,v2)

Upvotes: 6

y. bs
y. bs

Reputation: 542

val res = t1.map(t1Tup=>(t1Tup._1,t2.getOrElse(t1Tup._2,None)))

Upvotes: -4

Related Questions