sorted By
Начиная с Kotlin: 1.0
inline fun <T, R : Comparable<R>> Array<out T>.sortedBy(crossinline selector: (T) -> R?): List<T>
inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T>
Возвращает список всех элементов, отсортированных в естественном порядке сортировки по значению, возвращаемому указанной функцией selector.
Сортировка является стабильной. Это означает, что элементы, для которых selector вернула одинаковые значения, сохраняют взаимный порядок после сортировки.
Примеры
import kotlin.math.*
import kotlin.test.*
fun main() {
//sampleStart
class Dish(val name: String, val calories: Int, val tasteRate: Float) {
override fun toString(): String = "Dish($name: $calories cal, taste $tasteRate/5)"
}
val fridgeContent = listOf(Dish("🍨", 207, 4.7f), Dish("🥦", 34, 2.3f), Dish("🧃", 34, 4.9f))
val dullDishes = fridgeContent.sortedBy { it.tasteRate }
println(dullDishes) // [Dish(🥦: 34 cal, taste 2.3/5), Dish(🍨: 207 cal, taste 4.7/5), Dish(🧃: 34 cal, taste 4.9/5)]
val lightDishes = fridgeContent.sortedBy { it.calories }
// note that the sorting is stable, so the 🥦 is before the 🧃
println(lightDishes) // [Dish(🥦: 34 cal, taste 2.3/5), Dish(🧃: 34 cal, taste 4.9/5), Dish(🍨: 207 cal, taste 4.7/5)]
// the original collection remains unchanged
println(fridgeContent) // [Dish(🍨: 207 cal, taste 4.7/5), Dish(🥦: 34 cal, taste 2.3/5), Dish(🧃: 34 cal, taste 4.9/5)]
//sampleEnd
}
inline fun <R : Comparable<R>> ByteArray.sortedBy(crossinline selector: (Byte) -> R?): List<Byte>
inline fun <R : Comparable<R>> ShortArray.sortedBy(crossinline selector: (Short) -> R?): List<Short>
inline fun <R : Comparable<R>> IntArray.sortedBy(crossinline selector: (Int) -> R?): List<Int>
inline fun <R : Comparable<R>> LongArray.sortedBy(crossinline selector: (Long) -> R?): List<Long>
inline fun <R : Comparable<R>> FloatArray.sortedBy(crossinline selector: (Float) -> R?): List<Float>
inline fun <R : Comparable<R>> DoubleArray.sortedBy(crossinline selector: (Double) -> R?): List<Double>
inline fun <R : Comparable<R>> BooleanArray.sortedBy(crossinline selector: (Boolean) -> R?): List<Boolean>
inline fun <R : Comparable<R>> CharArray.sortedBy(crossinline selector: (Char) -> R?): List<Char>
Возвращает список всех элементов, отсортированных в естественном порядке сортировки по значению, возвращаемому указанной функцией selector.
Сортировка является стабильной. Это означает, что элементы, для которых selector вернула одинаковые значения, сохраняют взаимный порядок после сортировки.
Примеры
import kotlin.math.*
import kotlin.test.*
fun main() {
//sampleStart
val unsorted = intArrayOf(3, 1, 2, 4)
val sortedByRemainder = unsorted.sortedBy { it % 3 }
// the sorting is stable: the order of 1 (1 % 3 == 1) and 4 (4 % 3 == 1) was preserved
println(sortedByRemainder) // [3, 1, 4, 2]
val mapping = mapOf(1 to "one", 2 to "two", 3 to "three", 4 to "four")
val sortedByPronunciation = unsorted.sortedBy {
// take a key to sort by from the mapping
mapping.getOrDefault(it, "unknown")
}
// four < one < three < two, lexicographically
println(sortedByPronunciation) // [4, 1, 3, 2]
// the original array remains unchanged
println(unsorted.toList()) // [3, 1, 2, 4]
//sampleEnd
}
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/sorted-by.html