我只是在探索 kotlin 集合,我观察到了一个重要的行为。
val sports = listOf<Sports>(
Sports("cricket", "7"),
Sports("gilli", "10"),
Sports("lagori", "8"),
Sports("goli", "6"),
Sports("dabba", "4")
)
sports.sortedBy { it.rating } // sortedByDescending is to sort in descending
.forEach({ println("${it.name} ${it.rating}") })
}
class Sports(name: String, rating: String) {
var name: String = name
var rating: String = rating
}
Run Code Online (Sandbox Code Playgroud)
上面我只能得到sortedBy
方法,即以sorted
. 我不知道为什么我没有得到sortBy
和sortWith
操作。
任何人都可以用简单的语言对此进行解释。
好吧,这似乎是个愚蠢的问题。但是,有时即使是有经验的人也会为此苦苦挣扎。所以,我来回答这个
第一点,有两种列表类型。listOf
,mutableListOf
所以,如果你需要 sortBy、sortWith 或任何以 sort 开头的东西,那么你必须使用 mutableListOf
如果您想保持原始元素列表不变,请sorted
选择sort
内容或选择内容。
/**
* 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))
}
Run Code Online (Sandbox Code Playgroud)
/**
* 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.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
return sortedWith(compareBy(selector))
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2054 次 |
最近记录: |