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.
Because the sortWith will do the sorting in-place, we need to use a mutable collection. If we want the result returned as a new collection then we need to use the sortedWith method instead of the sortWith method. For descending order, we can use the reverse method or alternatively define the right Comparator.
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
if you want to keep original list of elements unchanged go with sorted
stuff or choose sort
stuff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With