thenComparator

inline fun <T> Comparator<T>.thenComparator(crossinline comparison: (a: T, b: T) -> Int): Comparator<T>(source)

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

Since Kotlin

1.1

Samples

import kotlin.test.*

fun main() { 
   //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
}
inline fun <T> Comparator<T>.thenComparator(crossinline comparison: (a: T, b: T) -> Int): Comparator<T>(source)

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

Since Kotlin

1.0

Samples

import kotlin.test.*

fun main() { 
   //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
}