1

Suppose I have a Map like

val x = Map(1 -> List("a", "b"), 2 -> List("a"), 3 -> List("a", "b"), 4 -> List("a"), 5 -> List("c")) 

How would I create from this a new Map where the keys are Lists of keys from x having the same value, e.g., how can I implement

def someFunction(m: Map[Int, List[String]]): Map[List[Int], List[String]] = // stuff that would turn x into // Map(List(1, 3) -> List("a", "b"), List(2, 4) -> List("a"), List(5) -> List("c")) 

?

1 Answer 1

3

You can convert the Map to a List and then use groupBy to aggregate the first element of each tuple:

x.toList.groupBy(_._2).mapValues(_.map(_._1)).map{ case (x, y) => (y, x) } // res37: scala.collection.immutable.Map[List[Int],List[String]] = // Map(List(2, 4) -> List(a), List(1, 3) -> List(a, b), List(5) -> List(c)) 

Or as @Dylan commented, use _.swap to switch the tuples' elements:

x.toList.groupBy(_._2).mapValues(_.map(_._1)).map(_.swap) 
Sign up to request clarification or add additional context in comments.

2 Comments

You beat me by a few seconds with pretty much the exact same solution, so I'll give you the +1 and add that you can use _.swap in the final map call.
@Dylan Ah, didn't know the _.swap method before. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.