简体   繁体   English

使用spark-shell进行排序和合并

[英]Sorting and Merging Using spark-shell

I have a string array in scala 我在scala中有一个字符串数组

Array[String] = Array(apple, banana, oranges, grapes, lichi, anar)

I have converted it into a format like this: 我已经将其转换成这样的格式:

Array[(Int, String)] = Array((5,apple), (6,banana), (7,oranges), (6,grapes), (5,lichi), (4,anar))

and i want output like this: 我想要这样的输出:

Array[(Int, String)] = Array((4,anar), (5,applelichi), (6,bananagrapes), (7,oranges))

means after sorting i want to add together the words with same key. 表示排序后,我想将具有相同键的单词加在一起。 i have done sorting. 我已经完成排序。 heres my code: 这是我的代码:

val a = sc.parallelize(List("apple","banana","oranges","grapes","lichi","anar"))
val b = a.map(x =>(x.length,x))
val c = b.sortBy(_._2)

You can use groupByKey() to do this and then merge the lists you get with mkString . 您可以使用groupByKey()进行此操作,然后将您获得的列表与mkString合并。 Small example using what you have (a,b are the same): 使用您所拥有的小例子(a,b相同):

val c = b.groupByKey().map{case (key, list) => (key, list.toList.sorted.mkString)}.sortBy(_._1)

c.collect() foreach println

Which will give you: 这会给你:

(4,anar)
(5,applelichi)
(6,bananagrapes)
(7,oranges)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM