0

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? Ideally without being really wasteful but performance isn't a great concern.

Thanks!

1 Answer 1

4

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. 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.

Sign up to request clarification or add additional context in comments.

2 Comments

You can just use flatten rather than flatMap(_.toSeq)
@Tim Oh, that's true. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.