Reputation: 5012
Getting unexpected output from map iteration of group result.
val res = List(3,3,5,7,7).groupBy(x => x)
//o/p res: scala.collection.immutable.Map[Int,List[Int]] = Map(5 -> List(5), 7 -> List(7, 7), 3 -> List(3, 3))
val res1 = List(3,3,5,7,7).groupBy(x => x).map(x => (x._2.size, x._1))
//error o:p => res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 5, 2 -> 3)
second function is returning partial result. Why it failed process number 7 ?
Upvotes: 0
Views: 48
Reputation: 15783
This happens because you are using as key the size of the list and both 7
and 3
have the same length so the latter overwrites the former, with different sizes:
scala> val res1 = List(3,3,5,7,7).groupBy(x => x).map(x => (x._2.size, x._1))
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 5, 2 -> 3)
scala> val res1 = List(3,3,5,7,7, 7).groupBy(x => x).map(x => (x._2.size, x._1))
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 5, 3 -> 7, 2 -> 3)
Upvotes: 4