Reputation: 139
I have a Seq[((Tuple A),(Tuple B))]
Is there an easy way to groupby Tuple A so I get Seq[(Tuple A, Seq[Tuple B])]
I.ve tried groupby(x => x.TupleA) but it throws a Mapping Exception: Do not know how to serialize key of tuple.
Upvotes: 4
Views: 5915
Reputation: 215117
I think this works. Use groupBy(_._1)
to group your sequence by the first element of the tuple, and collect the second element of the tuples in a list:
val s = Seq(((1,2,3), (4,5,6)), ((1,2,3), (5,6,7)), ((2,3,4), (4,5,6)))
s.groupBy(_._1).mapValues(_.map(_._2))
// res1: scala.collection.immutable.Map[(Int, Int, Int),Seq[(Int, Int, Int)]] =
// Map((1,2,3) -> List((4,5,6), (5,6,7)), (2,3,4) -> List((4,5,6)))
If you want the result to be a list instead of Map, use toList
to convert:
s.groupBy(_._1).mapValues(_.map(_._2)).toList
gives:
// List(((1,2,3),List((4,5,6), (5,6,7))), ((2,3,4),List((4,5,6))))
Upvotes: 8