原文: [Kotlin 集合對象的單條件和多條件排序 - Stars-One的雜貨小窩](https://stars-one.site/2023/06/14/kotlin-list-sort) 本文不是太難的東西,因為`sortedWith`之前沒怎麼用過,所以就記錄下 平常開發經常使用到List, ...
原文: Kotlin 集合對象的單條件和多條件排序 - Stars-One的雜貨小窩
本文不是太難的東西,因為sortedWith
之前沒怎麼用過,所以就記錄下
平常開發經常使用到List,Map等數據集合類型,也會經常遇到排序的問題,可以直接使用sortedBy
或sortedByDescending
排序
多條件則是使用sortedWith
,具體使用用例看見下文
單條件排序
方便起見,我們創建一個類Author
,用來保存數據
data class Author(val name:String,val age:Int,val height:Int)
val authorList = listOf(
Author("John", 30, 175),
Author("Alice", 25, 165),
Author("Bob", 25, 180),
Author("John1", 25, 180),
Author("Alice1", 30, 170)
)
authorList.sortedByDescending {
it.age
}
多條件排序
實際上,kotlin里提供了compareBy方法,方便開發者快速創建一個比較器的對象
val personList = listOf(
Person("John", 30, 175),
Person("Alice", 25, 165),
Person("Bob", 25, 180),
Person("John", 25, 180),
Person("Alice", 30, 170)
)
val sortedList = personList.sortedWith(compareBy(
{ it.name }, // 按姓名升序
{ -it.age }, // 按年齡降序
{ it.height } // 按身高升序
))
sortedList.forEach { println(it) }
compareBy
方法介紹:
compareBy 是 Kotlin 標準庫提供的一個函數,它可以幫助我們創建排序條件。該函數接收一個或多個 lambda 表達式,每個 lambda 表示一個排序條件。
compareBy 函數的返回值是一個 Comparator 對象,可以用於對集合中的元素進行排序。使用這個函數的好處是,可以將多個排序條件組合在一起,並且可以方便地擴展排序條件,而不必改變排序演算法的實現。
提問之前,請先看提問須知 點擊右側圖標發起提問
![Stars-One安卓學習交流群 Stars-One安卓學習交流群](http://pub.idqqimg.com/wpa/images/group.png)
![](https://img2020.cnblogs.com/blog/1210268/202003/1210268-20200316120825333-1551152974.png)
![](https://img2018.cnblogs.com/blog/1210268/201905/1210268-20190508151523126-971809604.gif)