使用Scala映射进行Erring输出

时间:2016-01-29 12:27:44

标签: scala

从组结果的地图迭代中获得意外输出。

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号进程失败?

1 个答案:

答案 0 :(得分:4)

这是因为您使用的是列表大小的密钥,73的长度相同,因此后者会覆盖前者,大小不同:

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)