NormalGuy
NormalGuy

Reputation: 45

Scala: How to merge lists by the first element of the tuple

Let say I have a list:

[(A, a), (A, b), (A, c), (B, a), (B, d)]  

How do I make that list into:

[(A, [a,b,c]), (B, [a,d])]  

with a single function?

Thanks

Upvotes: 3

Views: 1538

Answers (2)

Swadhin Shahriar
Swadhin Shahriar

Reputation: 46

Just doing groupBy won't give you the expected format you desire. So i suggest you write a custom method for this.

def groupTuples[A,B](seq: Seq[(A,B)]): List[(A, List[B])] = { 
   seq.
   groupBy(_._1).
   mapValues(_.map(_._2).toList).toList
}

Then then invoke it to get the desired result.

val t = Seq((1,"I"),(1,"AM"),(1, "Koby"),(2,"UP"),(2,"UP"),(2,"AND"),(2,"AWAY"))

groupTuples[Int, String](t)

Upvotes: 0

Tanjin
Tanjin

Reputation: 2452

The groupBy function allows you to achieve this:

scala> val list = List((1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'd'))
list: List[(Int, Char)] = List((1,a), (1,b), (1,c), (2,a), (2,d))

scala> list.groupBy(_._1) // grouping by the first item in the tuple

res0: scala.collection.immutable.Map[Int,List[(Int, Char)]] = Map(2 -> List((2,a), (2,d)), 1 -> List((1,a), (1,b), (1,c)))

Upvotes: 4

Related Questions