sortedByDescending
inline fun <T, R : Comparable<R>> Sequence<T>.sortedByDescending(crossinline selector: (T) -> R?): Sequence<T>(source)
Returns a sequence that yields elements of this sequence sorted descending according to natural sort order of the value returned by specified selector function.
The sort is stable. It means that elements for which selector returned equal values preserve their order relative to each other after sorting.
The operation is intermediate and stateful.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
//sampleStart
class Dish(val name: String, val calories: Int, val tasteRate: Float) {
override fun toString(): String = "Dish($name: $calories cal, taste $tasteRate/5)"
}
val fridgeContent = sequenceOf(Dish("π₯¦", 34, 2.3f), Dish("π§", 34, 4.9f), Dish("π¨", 207, 4.7f))
val tastyDishes = fridgeContent.sortedByDescending { it.tasteRate }
println(tastyDishes.toList()) // [Dish(π§: 34 cal, taste 4.9/5), Dish(π¨: 207 cal, taste 4.7/5), Dish(π₯¦: 34 cal, taste 2.3/5)]
val energeticDishes = fridgeContent.sortedByDescending { it.calories }
// note that the sorting is stable, so the π₯¦ is before the π§
println(energeticDishes.toList()) // [Dish(π¨: 207 cal, taste 4.7/5), Dish(π₯¦: 34 cal, taste 2.3/5), Dish(π§: 34 cal, taste 4.9/5)]
// the original sequence's state remains unchanged
println(fridgeContent.toList()) // [Dish(π₯¦: 34 cal, taste 2.3/5), Dish(π§: 34 cal, taste 4.9/5), Dish(π¨: 207 cal, taste 4.7/5)]
//sampleEnd
}