Kotlin sortBy sortedBysortedWithsortWith区别
Posted aikongmeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kotlin sortBy sortedBysortedWithsortWith区别相关的知识,希望对你有一定的参考价值。
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)
以上是关于Kotlin sortBy sortedBysortedWithsortWith区别的主要内容,如果未能解决你的问题,请参考以下文章
Kotlin sortBy sortedBysortedWithsortWith区别
Kotlin sortBy sortedBysortedWithsortWith区别
Kotlin之集合排序(sortBysortByDescending)