5.3.9 排序操作符
reversed(): List<T>
倒序排列集合元素。 代码示例
1. >>> val list = listOf(1,2,3)
2. >>> list.reversed()
3. [3, 2, 1]
这个函数,Kotlin是直接调用的java.util.Collections.reverse()方法。其相关代码如下:
1. public fun <T> Iterable<T>.reversed(): List<T> {
2. if (this is Collection && size <= 1) return toList()
3. val list = toMutableList()
4. list.reverse()
5. return list
6. }
8. public fun <T> MutableList<T>.reverse(): Unit {
9. java.util.Collections.reverse(this)
10. }
11. ```#### `sorted`和`sortedDescending`
13. 升序排序和降序排序。
15. 代码示例
17. ```kotlin
18. >>> val list = listOf(1,3,2)
19. >>> list.sorted()
20. [1, 2, 3]
21. >>> list.sortedDescending()
22. [3, 2, 1]
23. ```#### `sortedBy`和`sortedByDescending`
25. 可变集合MutableList的排序操作。根据函数映射的结果进行升序排序和降序排序。
26. 这两个函数定义如下:
28. ```kotlin
29. public inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) -> R?): Unit {
30. if (size > 1) sortWith(compareBy(selector))
31. }
32. public inline fun <T, R : Comparable<R>> MutableList<T>.sortByDescending(crossinline selector: (T) -> R?): Unit {
33. if (size > 1) sortWith(compareByDescending(selector))
34. }
代码示例
1. >>> val mlist = mutableListOf("abc","c","bn","opqde","")
2. >>> mlist.sortBy({it.length})
3. >>> mlist
4. [, c, bn, abc, opqde]
5. >>> mlist.sortByDescending({it.length})
6. >>> mlist
7. [opqde, abc, bn, c, ]
