3

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

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
NormalGuy
  • 45
  • 5
  • just use groupBy – nmat Mar 18 '17 at 08:04
  • What do you mean by "a single function"? Using `groupBy` will get you started but there is no single Standard Library method that will make that complete transformation. – jwvh Mar 18 '17 at 08:10
  • Possible duplicate of [How to merge two lists of tuples?](http://stackoverflow.com/questions/13074031/how-to-merge-two-lists-of-tuples) – jwvh Mar 18 '17 at 08:35

2 Answers2

4

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)))
Tanjin
  • 2,442
  • 1
  • 13
  • 20
0

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)