从组结果的地图迭代中获得意外输出。
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)
第二个函数返回部分结果。为什么7号进程失败?
答案 0 :(得分:4)
这是因为您使用的是列表大小的密钥,7
和3
的长度相同,因此后者会覆盖前者,大小不同:
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)