Careeroza
Sorting Collections
sorted, sortedBy, sortedWith
Example
data class Hotel(val name: String, val rating: Double, val price: Int)
fun main() {
println(listOf(5, 2, 9, 1).sorted())
println(listOf(5, 2, 9, 1).sortedDescending())
println(listOf("banana", "Apple", "cherry").sortedBy { it.lowercase() })
val hotels = listOf(
Hotel("Taj", 4.8, 12000), Hotel("Lemon Tree", 4.2, 4500),
Hotel("OYO Rooms", 3.9, 1500), Hotel("ITC", 4.8, 9000),
)
println(hotels.sortedBy { it.price }.map { it.name })
println(hotels.sortedByDescending { it.rating }.map { it.name })
// rating high to low, then price low to high
val best = hotels.sortedWith(compareByDescending<Hotel> { it.rating }.thenBy { it.price })
println(best.map { "${it.name}(${it.rating}, ${it.price})" })
}Output
[1, 2, 5, 9] [9, 5, 2, 1] [Apple, banana, cherry] [OYO Rooms, Lemon Tree, ITC, Taj] [Taj, ITC, Lemon Tree, OYO Rooms] [ITC(4.8, 9000), Taj(4.8, 12000), Lemon Tree(4.2, 4500), OYO Rooms(3.9, 1500)]
Note: sorted() returns a new list. MutableList.sort() and sortBy() sort in place and return Unit.