首先,foreach的分配是Unit,所以這不是你想要的。使用不可變的vals。目前還不清楚什麼格式的文件,所以你必須在那裏得到一個字符串。
val file = "1\ta\t24\n2\ta\t3\n3\tb\t6"
val lines = file.split("\n")
val nodes = lines.map(_.split("\t")).map(a => (a(1),a(2))).groupBy(_._1).map(a => (a._1,a._2.map(b => b._2.toInt).sum))
//Map(b -> 6, a -> 27)
這是一個大熱的一塌糊塗,所以我會試着打破它:
val lines = file.split("\n") //split string into array of lines
val nodes = lines.map(_.split("\t")) //split each line into array of strings
.map(a => (a(1),a(2))) //get just the second two items from the array as a tuple
.groupBy(_._1) //group by the first item in the tuple
.map(a => (a._1,a._2.map(b => b._2.toInt).sum)) //take each tuple and map the second value (an array of strings) into an array of ints and get the sum
如果你不喜歡的地圖的最終輸出可以方便地與toList
或地圖更改映射到任何你想要的。
什麼是'文件'的類型? – 2014-11-04 22:22:06
file應該是一個字符串,因爲它是通過'''file = sc.texFile(path)''' – 2014-11-04 22:23:17