W3cubDocs

/Kotlin

thenByDescending

inline fun <T> Comparator<T>.thenByDescending(
    crossinline selector: (T) -> Comparable<*>?
): Comparator<T>

Platform and version requirements: JVM

Creates a descending comparator using the primary comparator and 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 lengthComparator = compareBy<String> { it.length }
println(list.sortedWith(lengthComparator)) // [b, a, aa, bb]

val lengthThenStringDesc = lengthComparator.thenByDescending { it }
println(list.sortedWith(lengthThenStringDesc)) // [b, a, bb, aa]
//sampleEnd
}
inline fun <T, K> Comparator<T>.thenByDescending(
    comparator: Comparator<in K>, 
    crossinline selector: (T) -> K
): Comparator<T>

Platform and version requirements: JVM

Creates a descending comparator comparing values after the primary comparator defined them equal. It uses the selector function to transform values and then compares them with the given comparator.

import kotlin.test.*

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

val lengthComparator = compareBy<String> { it.length }
println(list.sortedWith(lengthComparator)) // [A, b, a, aa, bb]

val lengthThenCaseInsensitive = lengthComparator
        .thenByDescending(String.CASE_INSENSITIVE_ORDER) { it }
println(list.sortedWith(lengthThenCaseInsensitive)) // [b, A, a, bb, aa]
//sampleEnd
}

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