5.3.9 排序操作符
reversed(): List<T>
倒序排列集合元素。 代码示例
>>> val list = listOf(1,2,3)>>> list.reversed()[3, 2, 1]
这个函数,Kotlin是直接调用的java.util.Collections.reverse()方法。其相关代码如下:
public fun <T> Iterable<T>.reversed(): List<T> {if (this is Collection && size <= 1) return toList()val list = toMutableList()list.reverse()return list}public fun <T> MutableList<T>.reverse(): Unit {java.util.Collections.reverse(this)}```#### `sorted`和`sortedDescending`升序排序和降序排序。代码示例```kotlin>>> val list = listOf(1,3,2)>>> list.sorted()[1, 2, 3]>>> list.sortedDescending()[3, 2, 1]```#### `sortedBy`和`sortedByDescending`可变集合MutableList的排序操作。根据函数映射的结果进行升序排序和降序排序。这两个函数定义如下:```kotlinpublic inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) -> R?): Unit {if (size > 1) sortWith(compareBy(selector))}public inline fun <T, R : Comparable<R>> MutableList<T>.sortByDescending(crossinline selector: (T) -> R?): Unit {if (size > 1) sortWith(compareByDescending(selector))}
代码示例
>>> val mlist = mutableListOf("abc","c","bn","opqde","")>>> mlist.sortBy({it.length})>>> mlist[, c, bn, abc, opqde]>>> mlist.sortByDescending({it.length})>>> mlist[opqde, abc, bn, c, ]
当前内容版权归 JackChan1999 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 JackChan1999 .