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) }
}