compareBy

Common
JVM
JS
Native
1.0
fun <T> compareBy(
    vararg selectors: (T) -> Comparable<*>?
): Comparator<T>

Creates a comparator using the sequence of functions to calculate a result of comparison. The functions are called sequentially, receive the given values a and b and return Comparable objects. As soon as the Comparable instances returned by a function for a and b values do not compare as equal, the result of that comparison is returned from the Comparator.

import kotlin.test.*

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

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

println(sorted) // [a, b, aa, bb]
//sampleEnd
}
Common
JVM
JS
Native
1.0
inline fun <T> compareBy(
    crossinline selector: (T) -> Comparable<*>?
): Comparator<T>

Creates a 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(compareBy { it.length })

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

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

import kotlin.test.*

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

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

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