Scala的两个地图合并
问题描述:
如何合并如下所示的地图:
How can I merge maps like below:
val map1 = Map(1 -> "a", 2 -> "b")
val map2 = Map("a" -> "A", "b" -> "B")
合并后.
Merged = Map( 1 -> List("a", "A"), 2 -> List("b", "B"))
可以是List,Set或具有size属性的任何其他集合.
Can be List, Set or any other collection who has size attribute.
答
我不确定我确切地了解您要搜索的内容,但是要实现所提供示例的功能,您可以执行以下操作:
I'm not sure I understand what are you searching for exactly, but to achieve that for the provided example you could do:
val map1 = Map(1 -> "a", 2 -> "b")
val map2 = Map("a" -> "A", "b" -> "B")
map1.mapValues(value => (value, map2(value)))
但是,您应该小心地将a中的每个值都作为b中的键(我只是假设这是在提供的示例中发生的).
However you should be careful to have every value from a as a key in b (I just assumed this happens from the provided example).