6

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)

一些语法糖会很棒!

4

1 回答 1

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未映射的值 in lower

于 2012-11-26T17:50:06.037 回答