问题
I'm just exploring kotlin collection and I observed one important behavior.
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
}
above I can only get sortedBy
method i.e which starts with sorted
. I don't know why I'm not getting sortBy
and sortWith
operations.
can anyone give explanation for this in simple words.
回答1:
Ok, this seems to be silly question. But, sometimes even for experienced people struggled with this. So, I'll answer this
First point, There are two list types. listOf
, mutableListOf
So, if you need sortBy, sortWith or anything which starts with sort then you must use mutableListOf
- sort will be applied on original list. but not return anything.
- sorted will not change original list but returns new list after applying changes.
if you want to keep original list of elements unchanged go with sorted
stuff or choose sort
stuff.
来源:https://stackoverflow.com/questions/61208049/what-is-the-difference-between-sortby-sortedby-and-sortwith-sortedwith-in-ko