thenBy

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

Creates a comparator comparing values after the primary comparator defined them equal. It uses the function to transform value to a Comparable instance for comparison.

Samples

import samples.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   val list = listOf("aa", "b", "bb", "a")

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

val lengthThenString = lengthComparator.thenBy { it }
assertPrints(list.sortedWith(lengthThenString), "[a, b, aa, bb]") 
   //sampleEnd
}

inline fun <T, K> Comparator<T>.thenBy(comparator: Comparator<in K>, crossinline selector: (T) -> K): Comparator<T>

Creates a 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.

Samples

import samples.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   val list = listOf("A", "aa", "b", "bb", "a")

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

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