Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a value in one map with the value of another map, based on a pattern match?

I have a map that has a few key value pairs, and I would like a way to go through those pairs and attempt to match the keys with the value of another map. If there's a match the values are substituted for each other. In other words, if there's a match value of the second map is substituted for the value of the first map. If there is no match, it is not included in the result.

I've tried figuring out the logic use the scala .map function but I'm new to scala and can't quite figure it out.

For example, I have the following two scala Map[String, String]:

val lookupMap = Map("aaa" -> "apple", "bbb" -> "orange", "ccc" -> "banana")

val entriesMap = Map("foo" -> "ccc", "bar"-> "aaa", "baz" -> "zzz") 

I would like some way to get the following result:

val result = Map("foo" -> "banana", "bar" -> "apple")

Note: "baz" was not included because it did not match to anything in the lookup Map.

like image 928
jjaguirre394 Avatar asked Dec 23 '25 00:12

jjaguirre394


1 Answers

A for comprehension can clean that up.

val result = for {
               (k,ev) <- entriesMap
               lv     <- lookupMap.get(ev)
             } yield (k,lv)
//result: Map[String,String] = Map(foo -> banana, bar -> apple)
like image 83
jwvh Avatar answered Dec 24 '25 14:12

jwvh