撰写两张地图

时间:2012-11-26 17:41:43

标签: scala dictionary

Scala中是否有一个函数来组成两个映射,或者flatMap是一种合理的方法吗?

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)

一些语法糖会很棒!

1 个答案:

答案 0 :(得分:10)

如果您知道lower将包含caps中所有值的键,则可以使用mapValues

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

如果您不想要或不需要新的集合,只需要一个映射,那么使用andThen会更加惯用:

scala> val composed = caps andThen lower
composed: PartialFunction[String,String] = <function1>

scala> composed("A")
res1: String = a

这也假设caps中没有未在lower中映射的值。