W3cubDocs

/Kotlin

thenComparator

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T> Comparator<T>.thenComparator(
    crossinline comparison: (a: T, b: T) -> Int
): Comparator<T>

Creates a comparator using the primary comparator and function to calculate a result of comparison.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val list = listOf("c" to 1, "b" to 2, "a" to 1, "d" to 0, null to 0)

val valueComparator = compareBy<Pair<String?, Int>> { it.second }
val map1 = list.sortedWith(valueComparator).toMap()
println(map1) // {d=0, null=0, c=1, a=1, b=2}

val valueThenKeyComparator = valueComparator
    .thenComparator({ a, b -> compareValues(a.first, b.first) })
val map2 = list.sortedWith(valueThenKeyComparator).toMap()
println(map2) // {null=0, d=0, a=1, c=1, b=2}
//sampleEnd
}

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