scala的函数编程的排序

排序
在scala集合中,可以使用以下几种方式来进行排序
sorted默认排序
sortBy指定字段排序
sortWith自定义排序

默认排序 | Sorted
示例
定义一个列表,包含以下元素: 3, 1, 2, 9, 7
对列表进行升序排序
参考代码
scala scala> List(3,1,2,9,7).sorted
res16: List[Int] = List(1, 2, 3, 7, 9)
在这里插入图片描述
指定字段排序 | SortBy
根据传入的函数转换后,再进行排序
方法签名
scala def sortBy[B](f: (A) ⇒ B): List[A]
方法解析
| sortBy方法 | API | 说明 | | ---------- | ---------- | ------------------------------------------------------------ | | 泛型 | [B] | 按照什么类型来进行排序 | | 参数 | f: (A) ⇒ B | 传入函数对象
接收一个集合类型的元素参数
返回B类型的元素进行排序 | | 返回值 | List[A] | 返回排序后的列表 |
示例
有一个列表,分别包含几下文本行:“01 hadoop”, “02 flume”, “03 hive”, “04 spark”
请按照单词字母进行排序
参考代码
scala 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)
在这里插入图片描述
自定义排序 | SortWith
自定义排序,根据一个函数来进行自定义排序
方法签名
scala def sortWith(lt: (A, A) ⇒ Boolean): List[A]
方法解析
| sortWith方法 | API | 说明 | | ------------ | -------------------- | ------------------------------------------------------------ | | 参数 | lt: (A, A) ⇒ Boolean | 传入一个比较大小的函数对象
接收两个集合类型的元素参数
返回两个元素大小,小于返回true,大于返回false | | 返回值 | List[A] | 返回排序后的列表 |
示例
有一个列表,包含以下元素:2,3,1,6,4,5
使用sortWith对列表进行降序排序
参考代码
scala 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> res15.reverse
res18: List[Int] = List(6, 5, 4, 3, 2, 1)
在这里插入图片描述
使用下划线简写上述案例
参考代码
scala scala> val a = List(2,3,1,6,4,5)
a: List[Int] = List(2, 3, 1, 6, 4, 5)
在这里插入图片描述
// 函数参数只在函数中出现一次,可以使用下划线代替
scala> a.sortWith(_ < _).reverse
res19: List[Int] = List(6, 5, 4, 3, 2, 1)
在这里插入图片描述

发布了106 篇原创文章 · 获赞 301 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/qq_45765882/article/details/104244268