scala中 sorted,sortBy,sortWith语法使用

2023-05-30 11:26:02 买帖  | 投诉/举报

篇首语:本文由小编为大家整理,主要介绍了scala中 sorted,sortBy,sortWith语法使用相关的知识,希望对你有一定的参考价值。

排序
在scala集合中,可以使用以下几种方式来进行排序

sorted 默认排序
sortBy 指定字段排序
sortWith 自定义排序

默认排序 sorted

//示例:对列表进行升序排序scala> List(3,1,2,9,7).sortedres0: List[Int] = List(1, 2, 3, 7, 9)//示例:对列表进行升序排序scala> List(3,1,2,9,7).sorted.reverseres1: List[Int] = List(9, 7, 3, 2, 1)

指定字段排序 sortBy

根据传入的函数转换后,再进行排序

def sortBy[B](f: (A) ⇒ B): List[A]

示例:有一个列表,分别包含几下文本行:“01 hadoop”, “02 flume”, “03 hive”, “04 spark”

参考代码

scala> val a = List("01 hadoop", "02 flume", "03 hive", "04 spark")a: List[String] = List(01 hadoop, 02 flume, 03 hive, 04 spark) //按照字母升序scala> a.sortBy(_.split(" ")(1))res8: List[String] = List(02 flume, 01 hadoop, 03 hive, 04 spark)//按照数字降序scala> a.sortBy(_.split(" ")(0)).reverseres4: List[String] = List(04 spark, 03 hive, 02 flume, 01 hadoop)

自定义排序 sortWith

自定义排序,根据一个函数来进行自定义排序,类似在Java中实现Comparable接口。

def sortWith(lt: (A, A) ⇒ Boolean): List[A]

scala> val a = List(2,3,1,6,4,5)a: List[Int] = List(2, 3, 1, 6, 4, 5)scala> a.sortWith((x,y) => if (x<y) true else false)res15: List[Int] = List(1, 2, 3, 4, 5, 6)// 函数参数只在函数中出现一次,可以使用下划线代替scala> a.sortWith(_ < _).reverseres19: List[Int] = List(6, 5, 4, 3, 2, 1)

以上是关于scala中 sorted,sortBy,sortWith语法使用的主要内容,如果未能解决你的问题,请参考以下文章