2016-01-29 65 views
0

從組映射迭代獲取意外輸出。使用斯卡拉映射輸出錯誤

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號流程?

回答

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)