0

我的文本文件有以下数据:

10,14,16,19,52
08,09,12,20,45
55,56,70,78,53

我想按降序对每一行进行排序。我试过下面的代码

val file = sc.textFile("Maximum values").map(x=>x.split(","))
val sorted = file.sortBy(x=> -x(2).toInt)
sorted.collect()

我得到了以下输出

[[55, 56, 70, 78, 53], [10, 14, 16, 19, 52], [08, 09, 12, 20, 45]]

上面的结果表明整个列表已按降序排序。但我希望按降序对每个值进行排序

例如

[10,14,16,19,52],[08,09,12,20,45],[55,56,70,78,53]

应该

[52,19,16,14,10],[45,20,12,09,08],[78,70,56,55,53]

请抽出时间来回答这个问题。在此先感谢。

4

3 回答 3

0

这是一种方法(未经测试)

val reverseStringOrdering = Ordering[String].reverse
val file = sc.textFile("Maximum values").map(x=>x.split(",").sorted(reverseStringOrdering))
val sorted = file.sortBy(r => r, ascending = false)
sorted.collect()
于 2018-09-27T12:54:07.760 回答
0

Spark SQL方式,

import org.apache.spark.sql.functions._
val df = Seq(
 ("10","14","16","19","52"),
 ("08","09","12","20","45"),
 ("55","56","70","78","53")).toDF("C1", "C2","C3","C4","C5")

 df.withColumn("sortedCol", sort_array(array("C1", "C2","C3","C4","C5"), false))
  .select("sortedCol")     
  .show()

输出

+--------------------+
|           sortedCol|
+--------------------+
|[52, 19, 16, 14, 10]|
|[45, 20, 12, 09, 08]|
|[78, 70, 56, 55, 53]|
+--------------------+
于 2018-09-27T13:02:36.473 回答
0

检查这个。

val file = spark.sparkContext.textFile("in/sort.dat").map( x=> { val y = x.split(','); y.sorted.reverse.mkString(",") }  )
file.collect.foreach(println)

EDIT1: 不同的方法如何应用于上述代码。

scala> val a = "10,14,16,19,52"
a: String = 10,14,16,19,52

scala> val b = a.split(',')
b: Array[String] = Array(10, 14, 16, 19, 52)

scala> b.sorted
res0: Array[String] = Array(10, 14, 16, 19, 52)

scala> b.sorted.reverse
res1: Array[String] = Array(52, 19, 16, 14, 10)

scala> b.sorted.reverse.mkString(",")
res2: String = 52,19,16,14,10

scala> b.sorted.reverse.mkString("*")
res3: String = 52*19*16*14*10

scala>

编辑2:

val file = spark.sparkContext.textFile("in/sort.dat").map( x=> { val y = x.split(',').map(_.toInt); y.sorted.reverse.mkString(",") }  )
file.collect.foreach(println)
于 2018-09-27T13:06:19.940 回答