There’s always something in the list comprehensions within Scala that just jumps out to suprise me.

When doing a groupBy I used to always perform a mapValues on all the values after that fact. I always found it rather klugey, but it got the job done.

Recently when looking over the Scaladoc to refresh my memory on the outputs of groupBy, I found that there is a method called groupMap.

It’s signature is:

 def groupMap[K, B](key: ((K, V)) => K)(f: ((K, V)) => B): Map[K, Iterable[B]]

What does this do?

It performs the same grouping operations as groupBy, but for every value it finds for a group, it performs a mapping operation. This comes in handy because the groupBy operation tends to create a list of objects based on the key you selected, which is a little strange to repeat it’s self. But, that’s a good thing for flexibility when you need it.

Example

This example will show a list of objects (strings), and return a groupped map of the object and the corresponding indexes. This is good for a frequency map that determines where it was in the original index.

println(List("A", "A", "B", "C").zipWithIndex.groupMap(_._1)(_._2))

The output will be:

Map(A -> List(0, 1), B -> List(2), C -> List(3))

If you wanted to go futher, take a look at the groupMapReduce. It takes this one step futher and attempts to summarize all of the values that you mapped.