Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using groupBy on a List of Tuples in Scala

Tags:

scala

I tried to group a list of tuples in Scala.

The input:

val a = List((1,"a"), (2,"b"), (3,"c"), (1,"A"), (2,"B"))

I applied:

a.groupBy(e => e._1)

The output I get is:

Map[Int,List[(Int, String)]] = Map(2 -> List((2,b), (2,B)), 1 -> List((1,a), (1,A)), 3 -> List((3,c)))

This is slightly different with what I expect:

Map[Int,List[(Int, String)]] = Map(2 -> List(b, B), 1 -> List(a, A)), 3 -> List(c))

What can I do to get the expected output?


1 Answers

You probably meant something like this:

a.groupBy(_._1).mapValues(_.map(_._2))

or:

a.groupBy(_._1).mapValues(_.unzip._2)

Result:

Map(2 -> List(b, B), 1 -> List(a, A), 3 -> List(c))
like image 104
Andrey Tyukin Avatar answered Oct 29 '25 04:10

Andrey Tyukin