Scala group by mapping keys

scala

Say I have a map like this:

val m: Map[Int, String] = Map(1 -> "a", 2 -> "b", 3 -> "c", 4 -> "d", ...)

Say I have a function: def f(i: Int): String that I want to apply to the keys of this map. I then want to group by the resulting f(key) and concatenate all the strings (values) belonging to the same f(key) group.

Is there an efficient way to "groupByKey" while mapping the key in plain scala (no spark).

Best Answer

If I understand the situation, you have a Map...

val m: Map[K,V] = ...

...and a function/method that transforms the keys...

def f(k: K):J = ...  //K and J can be same type

...and you want to group the keys from the Map and then collect all the values from the Map into their new groups.

m.keys                 //Iterable[K]
 .toList               //List[K]
 .groupBy(f)           //Map[J,List[K]]
 .mapValues(_.map(m))  //Map[J,List[V]]

If your original V is itself a List then you could flatMap(), instead of map(), to flatten the results.

The toList step is optional. Without it the result is Map[J,Iterable[V]].

Related Topic