W3cubDocs

/Kotlin

compareByDescending

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T> compareByDescending(
    crossinline selector: (T) -> Comparable<*>?
): Comparator<T>

Creates a descending comparator using the function to transform value to a Comparable instance for comparison.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val list = listOf("aa", "b", "bb", "a")

val sorted = list.sortedWith(compareByDescending { it.length })

println(sorted) // [aa, bb, b, a]
//sampleEnd
}
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T, K> compareByDescending(
    comparator: Comparator<in K>, 
    crossinline selector: (T) -> K
): Comparator<T>

Creates a descending comparator using the selector function to transform values being compared and then applying the specified comparator to compare transformed values.

Note that an order of comparator is reversed by this wrapper.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val list = listOf('B', 'a', 'A', 'b')

val sorted = list.sortedWith(
    compareByDescending(String.CASE_INSENSITIVE_ORDER) { v -> v.toString() }
)

println(sorted) // [B, b, a, A]
//sampleEnd
}

© 2010–2019 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/compare-by-descending.html