简体   繁体   English

在Scala中将映射序列转换为键映射到值序列

[英]Transform Sequence of Maps into Map of Keys to Sequences of Values in Scala

I'm trying to turn a sequence of maps, like for instance 我正在尝试绘制一系列地图,例如

val input = Seq(Map("a" -> 1, "b" -> 2),
                Map("a" -> 10,  "c" -> 30),
                Map("b" -> 200, "c" -> 300, "d" -> 400))

into a map from the keys in those maps to the sequence of values they map to across each of the maps in the original sequence. 从那些映射中的键到它们在原始序列中跨每个映射映射到的值序列的映射。

So the above should transform into 所以上面应该变成

val output = Map("a" -> Seq(1, 10),
                 "b" -> Seq(2, 200),
                 "c" -> Seq(30, 300),
                 "d" -> Seq(400))

I can think of a few ways to go about this but I'm looking for a solution that is idiomatic or the best scala style for this sort of transformation? 我可以想到一些解决方法,但我正在寻找一种惯用的解决方案或这种转换的最佳Scala风格? Ideally without being really wasteful but performance isn't a great concern. 理想情况下,不会造成真正的浪费,但是性能并不是一个大问题。

Thanks! 谢谢!

You can do this: 你可以这样做:

val output = input.flatten.groupBy(_._1).mapValues(_.map(_._2))

It will first flatten your map into a Seq of all map entries. 它将首先将您的地图展平为所有地图条目的Seq Then it groups the map entries on their keys. 然后,将地图项按其键分组。 Finally, you map the values (which is now a list of map entries) to a list of map-values. 最后,将值(现在是映射条目列表)映射到映射值列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM