1

I have a sequence of tuples like below. Number of "x" and "y"s occurred in documents "abc" and "xyz"

Seq(("abc", Map("x" -> 1, "y" -> 2)), ("xyz", Map("x" -> 2, "y" -> 1)))

How can I create an output like below from this above sequence.

Seq(("x", Map("abc" -> 1, "xyz" -> 2)), ("y", Map("abc" -> 2, "xyz" -> 1)))
4
  • you might want describe how you expect your output based on input? Commented May 18, 2018 at 0:23
  • 2
    Yes. I will edit the question. Commented May 18, 2018 at 0:24
  • Does the order of first-level keys x and y actually matter in the output? The maps in the input are not sorted. Should the output be sorted? Commented May 18, 2018 at 0:35
  • No need. Your solution looks fine. Thanks. Commented May 18, 2018 at 0:40

1 Answer 1

3

Here is one possibility:

val s = Seq(
  ("abc", Map("x" -> 1, "y" -> 2)), 
  ("xyz", Map("x" -> 2, "y" -> 1))
)

val t = (for {
  (x, yvs) <- s 
  (y, v) <- yvs
} yield (y, (x, v)))
  .groupBy(_._1)
  .mapValues(_.unzip._2.toMap)

println(t)

This produces (up to random reordering of the unsorted keys):

Map(
  x -> Map(abc -> 1, xyz -> 2),
  y -> Map(abc -> 2, xyz -> 1)
)
Sign up to request clarification or add additional context in comments.

1 Comment

Was about to post pretty much the same but slightly more verbose. TIL about unzip. 👍

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.