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.0

Samples

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
}