Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 134 Β· Collections

Sorting and Comparators

Learn Kotlin sorting: sorted, sortedBy, sortedWith, compareBy, thenBy, Comparator, Comparable, null ordering, stable sorts and in-place sort versus copy, with runnable examples.

Ranking a leaderboard, listing files by date, showing products from cheapest to most expensive: sorting is everywhere. Kotlin's standard library gives you a small family of functions that cover nearly every case, and a single idea sits behind all of them: a comparator, a rule that says which of two elements comes first.

In this lesson you start with the simple sorted and sortedBy, learn how to sort by several criteria with compareBy and thenBy, make your own classes sortable with Comparable, and handle the awkward cases: nulls, case, numbers stored as text, and the difference between sorting a copy and sorting in place. Basic list knowledge from Lists is enough to follow along.

sorted, sortedBy and friends

The sorted family returns a new list and never touches the original, so it works on read-only collections too.

Kotlin The basic sort functions

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is:

  • [1, 3, 5, 7, 9] and [9, 7, 5, 3, 1], then the unchanged original [5, 3, 9, 1, 7].
  • [Fig, apple, banana, kiwi, pear] for words.sorted(). Strings sort by character code, so the capital F comes before every lowercase letter.
  • [apple, banana, Fig, kiwi, pear] for sortedBy { it.lowercase() }, which is what most people expect.
  • [Fig, pear, kiwi, apple, banana] sorted by length ascending, and [banana, apple, pear, kiwi, Fig] descending.
  • String.CASE_INSENSITIVE_ORDER gives the same case-insensitive result as the lowercase() trick, without creating a lowercase copy of each word for every comparison.
  • reversed() simply flips the existing order; it does not sort.

sortedBy { selector } is the workhorse. The selector extracts a sort key from each element, and the elements are ordered by comparing those keys. The key type must be Comparable: numbers, strings, booleans, Char and dates all qualify.

Stable sorting

Kotlin's sorts are stable: elements whose keys are equal keep their original relative order. That is more useful than it sounds, because it lets you sort in layers.

Kotlin Stable sort and ties

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get [(c, 1), (b, 2), (a, 2), (d, 2)] and [(b, 2), (a, 2), (d, 2), (c, 1)]. The three pairs with the value 2 come out as b, a, d both times: exactly their order in the input. Note that sortedByDescending is stable too; it is not "ascending, then reversed".

Several criteria: compareBy and thenBy

Sorting people by age is easy. But what about "by age, and for the same age by name"? You need a comparator that looks at more than one property. compareBy builds a comparator from selectors, and thenBy adds a tie-breaker.

Kotlin Multi-level sorting

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The six lines are:

  1. [Amy, Cat, Zed, Bob, Dan]: by age only. Amy and Cat (25) and Zed and Bob (30) keep their input order because of stability.
  2. [Amy, Cat, Bob, Zed, Dan]: age first, then name. Now Bob comes before Zed.
  3. [Dan, Bob, Zed, Amy, Cat]: age descending, but names still ascending among equals.
  4. [Cat, Bob, Zed, Amy, Dan]: city, then age, then name, using the vararg form of compareBy.
  5. [Cat, Zed, Bob, Amy, Dan]: two separate sorts. The second sort is stable, so within each city the people stay in the age order produced by the first sort. This "sort by the least important key first" trick works, but a single compareBy is clearer and does one pass.
  6. Dan: maxWithOrNull takes a comparator and returns the largest element; there are minWithOrNull, maxWith and minWith too.

You can also extend a comparator you already have. thenComparator { a, b -> ... } adds a tie-breaker written by hand, then(otherComparator) adds an existing comparator, and thenDescending(otherComparator) adds one in reverse order. reversed() flips the whole comparator:

Kotlin then, thenComparator, thenDescending

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The four lines are [Dan, Bob, Cat, Amy] (age, then city: Oslo before Rome; Bern before Oslo), [Dan, Bob, Cat, Amy] (age, then name descending), [Bob, Dan, Amy, Cat] (age, then name ascending) and [Amy, Cat, Bob, Dan] (age descending, equal ages keep input order).

Notice compareBy<Person> { it.age }. When you write compareBy as the start of a chain, Kotlin cannot infer the element type from the lambda alone, so you give it explicitly in angle brackets. In the vararg form compareBy({ ... }, { ... }) the type comes from sortedWith.

Writing a Comparator by hand

A Comparator<T> is just a function (a, b) -> Int that returns a negative number if a goes first, zero if they tie and a positive number if b goes first. You can write one yourself, flip it with .reversed(), and mix it with thenBy:

Kotlin Handwritten comparators

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [3, 2, 1], [ccc, bb, a], [1, 2, 3], [3, 2, 1], then -1, -1 and 0. naturalOrder() and reverseOrder() are ready-made comparators for any Comparable. The compareTo functions return negative, zero or positive; do not rely on the exact value -1, only on its sign.

Avoid subtracting numbers in a comparator (a - b) unless you know the values are small. For large Int values the subtraction can overflow and flip the sign, which produces a broken ordering and sometimes the error Comparison method violates its general contract!. Prefer compareValues(a, b), a.compareTo(b) or compareBy.

Comparable: sorting your own classes

If your class has one obvious natural order, implement Comparable<T>. Then sorted(), max(), min(), <, > and in a..b all work without a comparator.

Kotlin A Comparable class

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see [v1.9, v1.10, v2.0, v2.1], v2.1, true, true and [v2.1, v2.0, v1.10, v1.9]. Note that v1.9 comes before v1.10: the comparison is numeric, not textual. compareValuesBy is the helper for writing compareTo over several properties.

What happens if the class is not Comparable? The compiler refuses:

Kotlin sorted on a non-Comparable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The error is main.kt:5:19: error: candidate 'fun <T : Comparable<T>> Iterable<T>.sorted(): List<T>' is inapplicable because of a receiver type mismatch. In plain words: sorted() only exists for Iterable<T> where T : Comparable<T>, and Box is not. Fix it by implementing Comparable<Box>, or by calling boxes.sortedBy { it.size }, which needs only a comparable key.

Implement Comparable only when there is one natural, unsurprising order (versions, money amounts, dates). For everything else, such as "people by age" versus "people by name", pass a comparator at the call site. Otherwise the class has to pick a winner for all callers.

Strings, case, nulls and numbers in text

The default string order is by Unicode character code. That produces surprises that you should know about:

Kotlin Awkward sort cases

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The results:

  • [10, 9, Adam, Zoe, adam, zoe, Γ‰mile]: digits first, then all capitals, then lowercase, and the accented Γ‰ at the very end because its code is larger than every ASCII letter. This is rarely what a human wants.
  • [10, 9, Adam, adam, zoe, Zoe, Γ‰mile] for both case-insensitive versions. Γ‰ still lands last, because it is a different character from E. Proper alphabetical ordering for a language needs java.text.Collator, which respects locale rules.
  • [1, 2, 3, null, null] with nullsLast, and [null, null, 3, 2, 1] with nullsFirst plus reverseOrder. A list with null elements cannot be sorted with plain sorted(); wrap the comparator in nullsFirst or nullsLast, or remove the nulls with filterNotNull().
  • [10, 100, 9] for listOf("10", "9", "100").sorted(): the text sort puts "10" and "100" before "9", because it compares character by character. Sorting by toInt() gives [9, 10, 100].

Whenever numbers are stored as strings, convert them in the selector. The same goes for dates stored as text: parse them, or make sure the format sorts correctly (ISO 2026-03-09 does).

Sort a copy or sort in place

Functions starting with sort (no ed) change a mutable collection in place and return Unit. Functions ending in ed return a new collection.

Kotlin In place versus copy

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The lines are [5, 2, 8, 1], [1, 2, 5, 8], [1, 2, 5, 8], [a, b, c], [c, b, a], [1, 2, 3], [2, 1, 3], {a=2, b=1} and [a, b]. sortedArray() copies; sort() mutates the array itself, which is why the original changes only after the third println. asReversed() returns a reversed view without copying, useful for big lists. Maps cannot be sorted in place; sort their entries into a list, or use toSortedMap() to get a map ordered by key (see Maps).

Calling an in-place sort on a read-only list is a compile error:

Kotlin sort on a read-only list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports main.kt:3:8: error: unresolved reference 'sort' on receiver of type 'List<Int>'. Use sorted() for a read-only list, or create a mutableListOf / toMutableList() first. See Mutable Collections and Iterators.

Performance and design notes

  • Sorting costs O(n log n) comparisons. sortedBy { expensive(it) } calls the selector on every comparison, so a heavy selector runs about 2 * n * log n times. For expensive keys, compute them once (map { it to key(it) }, sort, then map back), or use a cheap precomputed property.
  • To get just the top few results of a large list, sorting everything is wasteful. maxByOrNull finds one in O(n); for the top k, sort, or use a java.util.PriorityQueue that keeps only the best k elements.
  • Sorting a list that is already nearly sorted is fast, because the JVM's TimSort exploits existing runs.
  • A comparator must be consistent: if a < b and b < c then a < c. Inconsistent comparators, often from a - b overflow or from comparing Double with a tolerance, can make the JVM throw an IllegalArgumentException mid-sort.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does val s = nums.sorted() do to the list nums?

    sorted() returns a new list and works on read-only collections. In-place sorting is sort() on a mutable list or array.
  2. 2. How do you sort people by age, and by name for equal ages?

    compareBy starts a comparator and thenBy adds a tie-breaker. Adding an Int and a String does not even compile into a sensible key.
  3. 3. Which order does listOf("b", "A", "a", "B").sorted() produce?

    Strings sort by character code, so all capital letters come before lowercase ones.
  4. 4. Why does listOf(Box(3), Box(1)).sorted() fail to compile when Box is a plain class?

    sorted() is declared for Iterable<T> where T : Comparable<T>. Use sortedBy { it.size } or implement Comparable<Box>.
  5. 5. What does it mean that Kotlin's sort is stable?

    Stability means ties stay in input order, which lets you sort in layers.

Summary

  • sorted(), sortedBy { }, sortedDescending() and sortedWith(comparator) return a new list; sort() and friends change a mutable list or array in place.
  • sortedBy needs a Comparable key; sortedWith takes a full Comparator.
  • Build multi-level comparators with compareBy { }.thenBy { }, compareByDescending or the vararg form compareBy({ }, { }).
  • Implement Comparable<T> for a class with one natural order; use compareValuesBy inside compareTo.
  • Kotlin sorts are stable, strings sort by character code (capitals first), and nulls need nullsFirst or nullsLast.
  • Avoid a - b in comparators; mind expensive selectors; use asReversed() for a free reversed view.

Next: Accessing and Searching