How to group a Seq[Array[(Int, Int)]]) by the seco

2019-09-22 06:38发布

问题:

I have a sequence of Seq[(1,0),(2,0),(2,0),(1,1),(1,1),(2,1)]

I would like to modify it to Seq[(1,2,2),(1,1,2)] grouped by the second value

of each map in the array.

I have tried .groupBy(_._2) but it doesn't work. It gives me

value _2 is not a member of scala.collection.immutable.Array[(Int,Int)]

Any ideas?

回答1:

Try this

val input = Seq((1,0),(2,0),(2,0),(1,1),(1,1),(2,1))
input.groupBy(_._2).collect{
  case e => e._2.map(_._1)
}
//res3: scala.collection.immutable.Iterable[Seq[Int]] = List(List(1, 1, 2), List(1, 2, 2))


回答2:

If you have scala.collection.immutable.Array[(Int, Int)] you just need to select the second value for group and select only first values

data.groupBy(_._2).mapValues(x => x.map(_._1)).map(_._2).toList 

This will give you List[Array[Int]]

Hope this helps!



标签: scala