组成两张地图 [英] Composing two maps
本文介绍了组成两张地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Scala中是否有一个功能可以组成两张地图?flatMap是一种明智的方法吗?
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)
一些语法糖会很棒!
推荐答案
如果您知道lower
将包含caps
中所有值的键,则可以使用mapValues
:
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)
如果您不想或不需要新集合,只需映射,使用andThen
会更惯用:
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
这还假设caps
中没有映射的值,而lower
中没有映射的值.
This also assumes there aren't values in caps
that aren't mapped in lower
.
这篇关于组成两张地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文