jtitusj
jtitusj

Reputation: 3084

Scala: Better groupBy approach

Given an array with entries of the form (key, (index, rating)), for example:

val samp = Array((0, (1, 0.005)), (1, (1, 0.306)), (0, (0, 0.231)), (2, (2, 0.908)), (0, (2, 0.542)), (2, (1, 0.091)))

I want to transform this into

Array((key1, Array((index1, rating1), (index2, rating2), ...), (key2, Array((index1, rating1), (index2, rating2), ...)), ...)

To get this result, I did the following code:

samp.groupBy(_._1).map{ case (k, v) => (k, v.map(_._2)) }.toArray

which gives me:

Array((2,Array((2,0.908), (1,0.091))), (1,Array((1,0.306))), (0,Array((1,0.005), (0,0.231), (2,0.542))))

The code gives me what I want but I just want to find out if there are better ways of doing this since I'm fairly new to scala. Thanks!

Upvotes: 0

Views: 80

Answers (1)

Jean Logeart
Jean Logeart

Reputation: 53839

Maybe just use mapValues:

samp.groupBy(_._1).mapValues(_.map(_._2)).toArray

Upvotes: 5

Related Questions