Composing two maps

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

Is there a function in Scala to compose two maps or is flatMap a sensible approach?

scala> val caps: Map[String, Int] = Map(("A", 1), ("B", 2)) caps: Map[String,Int] = Map(A -> 1, B -> 2)  scala> val lower: Map[Int, String] = Map((1, "a"), (2, "b")) lower: Map[Int,String] = Map(1 -> a, 2 -> b)  scala> caps.flatMap {      | case (cap, idx) => Map((cap, lower(idx)))      | } res1: scala.collection.immutable.Map[String,String] = Map(A -> a, B -> b) 

Some syntactic sugar would be great!

回答1:

If you know lower will contain keys for all the values in caps, you can use mapValues:

scala> caps mapValues lower res0: scala.collection.immutable.Map[String,String] = Map(A -> a, B -> b) 

If you don't want or need a new collection, just a mapping, it's a little more idiomatic to use andThen:

scala> val composed = caps andThen lower composed: PartialFunction[String,String] = <function1>  scala> composed("A") res1: String = a 

This also assumes there aren't values in caps that aren't mapped in lower.



文章来源: Composing two maps
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!