Sorting
suggest changeKotlin's standard library has a sorting function for almost every situation, so you rarely need to write a sort yourself. What you do need to know is which function to call:
sorted()/sortedDescending()return a new sorted list, using the natural order of the elementssort()/sortDescending()sort aMutableListor an array in placesortedBy { }/sortedByDescending { }sort by a key extracted from each elementsortedWith(comparator)sorts with aComparator, built withcompareBy,thenByand friends
The naming rule is consistent: functions ending in -ed (sorted, sortedBy, sortedWith) leave the original alone and return a new collection, while the imperative forms (sort, sortBy, sortWith) modify the receiver and return Unit.
All of these sorts are stable: elements that compare as equal keep their original relative order. This is what makes sorting by several keys predictable.
Sorting in natural order
Numbers, strings, characters, dates and anything else that implements Comparable have a natural order:
fun main() {
val numbers = listOf(5, 2, 8, 1, 9)
println(numbers.sorted())
println(numbers.sortedDescending())
println(numbers) // unchanged
val words = listOf("banana", "apple", "Cherry", "Apple")
println(words.sorted())
}
[1, 2, 5, 8, 9]
[9, 8, 5, 2, 1]
[5, 2, 8, 1, 9]
[Apple, Cherry, apple, banana]
Strings are compared by UTF-16 code units, so all uppercase letters come before all lowercase letters. The section on case-insensitive and locale-aware sorting below shows how to fix that.
A read-only List has no sort() function. To sort in place you need a MutableList:
fun main() {
val list = mutableListOf(5, 2, 8, 1, 9)
list.sort()
println(list)
list.sortDescending()
println(list)
}
[1, 2, 5, 8, 9]
[9, 8, 5, 2, 1]
Arrays
Arrays can be sorted in place, partially, or copied into a new sorted array:
fun main() {
val arr = intArrayOf(5, 2, 8, 1, 9)
val copy = arr.sortedArray() // new IntArray, arr unchanged
println(copy.contentToString())
arr.sort() // in place
println(arr.contentToString())
val part = intArrayOf(9, 7, 5, 3, 1)
part.sort(1, 4) // sort only indexes 1, 2 and 3
println(part.contentToString())
val names = arrayOf("Carol", "alice", "Bob")
names.sortWith(String.CASE_INSENSITIVE_ORDER)
println(names.contentToString())
}
[1, 2, 5, 8, 9]
[1, 2, 5, 8, 9]
[9, 3, 5, 7, 1]
[alice, Bob, Carol]
sorted() called on an array returns a List, not an array. Use sortedArray() when you want to stay with arrays.
Sorting by a key: sortedBy
Most of the time you sort objects by one of their properties. sortedBy takes a lambda that returns the sort key:
data class Person(val name: String, val age: Int, val city: String)
val people = listOf(
Person("Alice", 32, "Paris"),
Person("Bob", 25, "London"),
Person("Carol", 32, "Berlin"),
Person("Dave", 25, "Paris"),
Person("Eve", 41, "London"),
)
fun main() {
println(people.sortedBy { it.age }.map { it.name })
println(people.sortedByDescending { it.age }.map { it.name })
println(people.sortedBy { it.name.length }.map { it.name })
}
[Bob, Dave, Alice, Carol, Eve]
[Eve, Alice, Carol, Bob, Dave]
[Bob, Eve, Dave, Alice, Carol]
Notice stability at work: Bob and Dave are both 25, and Bob comes first in every result because he comes first in the input.
The key can be any Comparable type, including nullable ones. The in-place version on a MutableList is sortBy:
val mutablePeople = people.toMutableList()
mutablePeople.sortBy { it.city }
Sorting by multiple keys
For "sort by city, then by name" build a Comparator with compareBy and pass it to sortedWith:
fun main() {
val byCityThenName = people.sortedWith(compareBy({ it.city }, { it.name }))
println(byCityThenName.map { "${it.city}/${it.name}" })
// property references work too
val byAgeThenName = people.sortedWith(compareBy(Person::age, Person::name))
println(byAgeThenName.map { "${it.age}/${it.name}" })
}
[Berlin/Carol, London/Bob, London/Eve, Paris/Alice, Paris/Dave]
[25/Bob, 25/Dave, 32/Alice, 32/Carol, 41/Eve]
When the keys need different directions, chain thenBy and thenByDescending:
fun main() {
val c1 = compareBy<Person> { it.age }.thenByDescending { it.name }
println(people.sortedWith(c1).map { "${it.age}/${it.name}" })
val c2 = compareByDescending<Person> { it.age }.thenBy { it.city }
println(people.sortedWith(c2).map { "${it.age}/${it.city}" })
// reverse an existing comparator
println(people.sortedWith(c1.reversed()).map { it.name })
}
[25/Dave, 25/Bob, 32/Carol, 32/Alice, 41/Eve]
[41/London, 32/Berlin, 32/Paris, 25/London, 25/Paris]
[Eve, Alice, Carol, Bob, Dave]
The explicit type argument in compareBy<Person> is needed when the comparator is created on its own, because the compiler has no other way to infer the type of it. Inside a sortedWith(...) call it can usually be left out.
A Comparator is a regular value, so you can store common orderings in a companion object and reuse them:
data class Product(val name: String, val price: Double, val rating: Int) {
companion object {
val ByPrice = compareBy<Product> { it.price }
val ByBest = compareByDescending<Product> { it.rating }.thenBy { it.price }
}
}
fun main() {
val products = listOf(
Product("Mouse", 25.0, 4),
Product("Keyboard", 80.0, 5),
Product("Cable", 5.0, 3),
Product("Monitor", 250.0, 5),
)
println(products.sortedWith(Product.ByPrice).map { it.name })
println(products.sortedWith(Product.ByBest).map { it.name })
}
[Cable, Mouse, Keyboard, Monitor]
[Keyboard, Monitor, Mouse, Cable]
Making your own types Comparable
If a type has one obvious order, implement Comparable. Then sorted(), max(), min(), <, > and ranges all work with it. compareValuesBy makes a multi-field compareTo a one-liner:
data class Version(val major: Int, val minor: Int, val patch: Int) : Comparable<Version> {
override fun compareTo(other: Version): Int =
compareValuesBy(this, other, Version::major, Version::minor, Version::patch)
override fun toString() = "$major.$minor.$patch"
companion object {
fun parse(s: String): Version {
val (a, b, c) = s.split(".").map { it.toInt() }
return Version(a, b, c)
}
}
}
fun main() {
val raw = listOf("1.10.0", "1.2.3", "2.0.0", "1.2.10")
println(raw.sorted()) // string order: wrong for versions
val versions = raw.map(Version::parse)
println(versions.sorted())
println(versions.max())
println(Version(1, 2, 3) < Version(1, 10, 0))
println(Version(1, 5, 0) in Version(1, 0, 0)..Version(2, 0, 0))
}
[1.10.0, 1.2.10, 1.2.3, 2.0.0]
[1.2.3, 1.2.10, 1.10.0, 2.0.0]
2.0.0
true
true
compareTo should be consistent with equals: if a.compareTo(b) == 0 then ideally a == b. A data class whose compareTo uses all of its properties satisfies this automatically. It matters for sorted sets and maps, as shown in the section on sorted collections below.
Case-insensitive and locale-aware sorting
For a simple case-insensitive sort use String.CASE_INSENSITIVE_ORDER:
fun main() {
val words = listOf("banana", "apple", "Cherry", "Apple")
println(words.sortedWith(String.CASE_INSENSITIVE_ORDER))
println(words.sortedBy { it.lowercase() }) // same result, allocates a string per comparison
}
[apple, Apple, banana, Cherry]
[apple, Apple, banana, Cherry]
Text shown to people should be sorted with a java.text.Collator, which knows the alphabet rules of a language: accented letters sort next to their base letters, and some languages put certain letters after z:
import java.text.Collator
import java.util.Locale
fun main() {
val names = listOf("Zoë", "zebra", "Émile", "eagle", "Ångström", "apple")
println(names.sorted())
println(names.sortedWith(Collator.getInstance(Locale.ENGLISH)))
println(names.sortedWith(Collator.getInstance(Locale.forLanguageTag("sv-SE"))))
}
[Zoë, apple, eagle, zebra, Ångström, Émile]
[Ångström, apple, eagle, Émile, zebra, Zoë]
[apple, eagle, Émile, zebra, Zoë, Ångström]
Collator implements Comparator<Any>, so it can be passed to sortedWith for a list of strings. To sort objects by a localized name, combine it with a selector: compareBy(collator) { it.name }.
Natural ("human") order for strings with numbers
File names like file2.txt and file10.txt sort the wrong way as plain strings, because '1' < '2'. A natural-order comparator compares runs of digits as numbers:
private val chunk = Regex("\\d+|\\D+")
fun naturalCompare(a: String, b: String): Int {
val pa = chunk.findAll(a).map { it.value }.toList()
val pb = chunk.findAll(b).map { it.value }.toList()
for (i in 0 until minOf(pa.size, pb.size)) {
val x = pa[i]
val y = pb[i]
val cmp = if (x[0] in '0'..'9' && y[0] in '0'..'9') {
x.toBigInteger().compareTo(y.toBigInteger())
} else {
x.compareTo(y, ignoreCase = true)
}
if (cmp != 0) return cmp
}
return pa.size.compareTo(pb.size)
}
val NaturalOrder = Comparator<String> { a, b -> naturalCompare(a, b) }
fun main() {
val files = listOf("file10.txt", "file2.txt", "File1.txt", "file1.txt", "file20.txt")
println(files.sorted())
println(files.sortedWith(NaturalOrder))
}
[File1.txt, file1.txt, file10.txt, file2.txt, file20.txt]
[File1.txt, file1.txt, file2.txt, file10.txt, file20.txt]
toBigInteger() avoids overflow on very long digit runs. If you sort large lists with this, split each string into chunks once up front instead of inside every comparison.
Sorting with nulls
sorted() isn't available on a List<Int?>, because null has no natural order. Decide where nulls go with nullsFirst() or nullsLast():
fun main() {
val scores = listOf(3, null, 1, null, 2)
println(scores.sortedWith(nullsFirst()))
println(scores.sortedWith(nullsLast()))
println(scores.sortedWith(nullsLast(reverseOrder())))
}
[null, null, 1, 2, 3]
[1, 2, 3, null, null]
[3, 2, 1, null, null]
When the selector returns a nullable value, sortedBy puts nulls first. To put them last, pass a comparator for the key to compareBy:
data class Task(val title: String, val due: Int?)
fun main() {
val tasks = listOf(
Task("Write report", 3),
Task("Call Bob", null),
Task("Pay rent", 1),
Task("Read book", null),
)
println(tasks.sortedBy { it.due }.map { it.title })
println(tasks.sortedWith(compareBy(nullsLast<Int>()) { it.due }).map { it.title })
}
[Call Bob, Read book, Pay rent, Write report]
[Pay rent, Write report, Call Bob, Read book]
Sorting maps
A Map has no order to sort in place. Instead, sort its entries and either use the resulting list or build a new map from it. A LinkedHashMap (what mapOf and associate create) keeps insertion order:
fun main() {
val wordCounts = mapOf("the" to 12, "kotlin" to 7, "sort" to 7, "a" to 15)
// top 3 by count
println(wordCounts.entries.sortedByDescending { it.value }.take(3))
// by count descending, ties broken alphabetically
val ranked = wordCounts.toList()
.sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first })
println(ranked)
// a new map ordered by value
println(wordCounts.entries.sortedBy { it.value }.associate { it.toPair() })
// a map that stays sorted by key
println(wordCounts.toSortedMap())
}
[a=15, the=12, kotlin=7]
[(a, 15), (the, 12), (kotlin, 7), (sort, 7)]
{kotlin=7, sort=7, the=12, a=15}
{a=15, kotlin=7, sort=7, the=12}
Sorted collections
If you add elements over time and always need them in order, a sorted collection is cheaper than re-sorting a list after every insert. sortedSetOf creates a java.util.TreeSet and sortedMapOf / toSortedMap create a TreeMap:
fun main() {
val set = sortedSetOf(5, 1, 3, 1, 9)
println(set)
println("${set.first()} ${set.last()}")
println(set.headSet(5)) // elements < 5
println(set.ceiling(4)) // smallest element >= 4
val byLength = sortedSetOf(compareBy<String> { it.length }, "ccc", "a", "bb", "dd")
println(byLength)
}
[1, 3, 5, 9]
1 9
[1, 3]
5
[a, bb, ccc]
Look at the last line: "dd" is gone. A TreeSet uses the comparator, not equals, to detect duplicates, and "bb" and "dd" have the same length. Add a tie-breaker so that only truly equal elements compare as 0: compareBy<String> { it.length }.thenBy { it }.
Top N, min and max
You don't need to sort a whole list to find its largest element. maxBy, minBy, maxOf and their OrNull variants do it in one pass:
fun main() {
println(people.maxByOrNull { it.age }?.name)
println(people.minOf { it.age })
println(people.sortedByDescending { it.age }.take(2).map { it.name })
}
Eve
25
[Eve, Alice]
sortedBy...take(n) is fine for small lists. For the top N of a very large collection or a stream of items, a bounded PriorityQueue uses O(N) memory and O(size * log N) time:
import java.util.PriorityQueue
fun <T> topN(items: Iterable<T>, n: Int, comparator: Comparator<T>): List<T> {
val heap = PriorityQueue(comparator) // smallest element at the head
for (item in items) {
heap.add(item)
if (heap.size > n) heap.poll() // drop the smallest
}
return heap.sortedWith(comparator.reversed())
}
fun main() {
val values = listOf(42, 7, 99, 15, 63, 8, 71)
println(topN(values, 3, naturalOrder()))
}
[99, 71, 63]
Searching a sorted list
On a sorted list, binarySearch finds an element in O(log n). When the element is missing it returns -(insertionPoint) - 1, which tells you where to insert it to keep the list sorted:
fun main() {
val list = mutableListOf(1, 3, 5, 7, 9)
println(list.binarySearch(7))
println(list.binarySearch(4))
val idx = list.binarySearch(4)
list.add(if (idx < 0) -idx - 1 else idx, 4)
println(list)
val byAge = people.sortedBy { it.age }
println(byAge.binarySearchBy(41) { it.age })
}
3
-3
[1, 3, 4, 5, 7, 9]
4
The list must be sorted by the same order you search with; otherwise the result is undefined.
Performance notes
- Sorting objects uses TimSort: O(n log n), and very fast on input that is already partly sorted. Primitive arrays (
IntArray,DoubleArray, ...) use a dual-pivot quicksort, which isn't stable, but for primitives you can't tell the difference. sortedBy { key(it) }callskeytwice per comparison, i.e. O(n log n) times. If the key is expensive (parsing, I/O, regex), compute it once per element:
val sorted = items
.map { it to expensiveKey(it) }
.sortedBy { it.second }
.map { it.first }
sorted()on a sequence is a stateful operation: it has to read the entire sequence before it can produce the first element, so it doesn't work on infinite sequences.- Sorting a list copies it into an array, sorts the array and wraps it. If you're going to sort a
MutableListyou own anyway,sort()in place avoids that copy.
Pitfalls
sort() returns Unit. This compiles, but result is Unit, not a list:
val result = mutableListOf(3, 1, 2).sort() // wrong
val sorted = listOf(3, 1, 2).sorted() // right
Don't subtract in comparators. a - b overflows for large values and silently produces the wrong order:
fun main() {
val values = listOf(1, Int.MIN_VALUE, -1)
println(values.sortedWith(Comparator { a, b -> a - b })) // broken
println(values.sortedWith(Comparator { a, b -> a.compareTo(b) }))
}
[1, -2147483648, -1]
[-2147483648, -1, 1]
Use compareTo, compareValues, or compareBy instead.
Comparators must be consistent. If compare(a, b) < 0 and compare(b, c) < 0, then compare(a, c) must be negative too, and the result must not change between calls. Comparators that use random numbers or mutable state can throw IllegalArgumentException: Comparison method violates its general contract! on larger inputs. To shuffle, use shuffled().
Floating point. sorted() on doubles uses Double.compareTo, which orders -0.0 before 0.0 and puts NaN last:
fun main() {
println(listOf(3.0, Double.NaN, 0.0, -0.0, 1.0).sorted())
}
[-0.0, 0.0, 1.0, 3.0, NaN]
Don't mutate objects while they're in a sorted collection. Changing a property that a TreeSet or TreeMap uses for ordering corrupts it: lookups and removals start failing. Remove the element, change it, and add it back, or better, use immutable data classes with val properties.
For an overview of the other collection operations, see Collections.