Kotlin sortBy 、sortedBy、sortedWith、sortWith区别

这篇博客探讨了Kotlin中对列表进行排序的方法,包括`sortedBy`函数创建新排序列表和`sortBy`方法就地排序列表。`sortedBy`返回一个新的已排序列表,保持相等元素的相对顺序,而`sortBy`直接修改原列表。博客还展示了这些函数的使用示例,强调了排序的稳定性,并提供了相关函数的源码解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码

import kotlin.test.*

fun main(args: Array<String>) {

val list = mutableListOf("aaa", "cc", "bbbb")
val sorted = list.sortedBy { it.length }

println(list) // [aaa, cc, bbbb]
println(sorted) // [cc, aaa, bbbb]
list.sortBy{ it.length}
println(list)//[cc, aaa, bbbb]

sortBy Sorts elements in the list 就地排序

/**
 * Sorts elements in the list in-place according to natural sort order of the value returned by specified [selector] function.
 * 
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 */
public inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) -> R?): Unit {
    if (size > 1) sortWith(compareBy(selector))
}


sortedBy Returns a list of all elements sorted 返回新的list

/**
 * Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector] function.
 * 
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 * 
 * @sample samples.collections.Collections.Sorting.sortedBy
 */
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
    return sortedWith(compareBy(selector))
}
expect fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit
/**
 * Returns a list of all elements sorted according to the specified [comparator].
 * 
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 */
public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T> {
    if (this is Collection) {
       if (size <= 1) return this.toList()
       @Suppress("UNCHECKED_CAST")
       return (toTypedArray<Any?>() as Array<T>).apply { sortWith(comparator) }.asList()
    }
    return toMutableList().apply { sortWith(comparator) }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值