Use people.sortedBy { it.age }. It returns a new list ordered by the key you pick, and sortedByDescending gives the reverse. For several fields, pass a comparator: sortedWith(compareBy({ it.dept }, { it.name })), or chain compareBy<Employee> { it.dept }.thenByDescending { it.salary } when the directions differ. To sort a MutableList in place instead of making a copy, call sortBy, sortByDescending or sortWith.
Kotlin sorts with extension functions on the collection, so there is no Collections.sort and no Comparator.comparing to import. The functions come in pairs: sortedBy returns a sorted copy and works on any List, while sortBy reorders a MutableList or an array and returns nothing. For more than one key you build a Comparator with compareBy, thenBy and thenByDescending. The sections below cover one key, several keys, nullable keys, sorting in place, a natural order with Comparable, and what a stable sort lets you rely on, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1sortedBy and sortedByDescendingRecommended
sortedBy takes a lambda that returns the key to sort on, here it.age, and returns a new List in ascending order of that key. The key can be any Comparable value: a number, a String, a LocalDate, an enum. A property reference such as Person::name works in place of the lambda. The list you start from is not touched, so this works on a read-only List from listOf. When you only need the smallest or largest element, minBy and maxBy find it without sorting.
data class Person(val name: String, val age: Int) fun main() { val people = listOf( Person("Mia", 31), Person("Ana", 25), Person("Leo", 42), Person("bob", 25), ) // sortedBy returns a new list, ordered by the key you pick val byAge = people.sortedBy { it.age } println(byAge) // Largest first println(people.sortedByDescending { it.age }.map { it.name }) // A property reference works as the key too println(people.sortedBy(Person::name).map { it.name }) // Strings compare by character code: lowercase the key to ignore case println(people.sortedBy { it.name.lowercase() }.map { it.name }) // The original list is unchanged println(people.map { it.name }) // Only need the smallest or the largest? No sort needed println(people.minBy { it.age }) println(people.maxByOrNull { it.age }?.name) }
Output
By age, Ana and bob (both 25) come first and Leo (42) last; sortedByDescending gives [Leo, Mia, Ana, bob]. Sorting by name puts bob last, after Mia, because uppercase letters come before lowercase ones in character order; the lowercase() key gives the alphabetical [Ana, bob, Leo, Mia]. The last list printed before minBy is still [Mia, Ana, Leo, bob], the original order. minBy throws NoSuchElementException on an empty list; maxByOrNull returns null instead.
2Sort by multiple fields: compareBy and thenBy
sortedBy takes one key. For more, use sortedWith and a Comparator. compareBy takes several key lambdas (or property references) and compares by the first, falling back to the next only on a tie. All keys then sort ascending. When one key should go the other way, start a chain with compareBy<Employee> { … } or compareByDescending and add thenBy and thenByDescending; the type argument is needed because the first lambda alone doesn't say what it is. These replace Java's Comparator.comparing(…).thenComparing(…).
data class Employee(val name: String, val dept: String, val salary: Int) fun main() { val staff = listOf( Employee("Mia", "Sales", 5200), Employee("Ana", "IT", 6100), Employee("Leo", "Sales", 4800), Employee("Zoe", "IT", 6100), Employee("Ben", "IT", 5500), ) // By department, then by name within each department val byDeptName = staff.sortedWith(compareBy({ it.dept }, { it.name })) byDeptName.forEach { println("${it.dept} ${it.name}") } println() // Property references read well when every key is ascending val byDeptPay = staff.sortedWith( compareBy(Employee::dept, Employee::salary), ) println(byDeptPay.map { it.name }) // Mixed directions: chain thenBy and thenByDescending val byDeptTopPay = compareBy<Employee> { it.dept } .thenByDescending { it.salary } .thenBy { it.name } staff.sortedWith(byDeptTopPay).forEach { println("${it.dept} ${it.salary} ${it.name}") } println() // Descending first key: compareByDescending val topPay = compareByDescending<Employee> { it.salary }.thenBy { it.name } println(staff.sortedWith(topPay).map { it.name }) // reversed() flips every key of a comparator println(staff.sortedWith(byDeptTopPay.reversed()).map { it.name }) }
Output
IT sorts before Sales, and inside each department the names are in order. By department and salary, Ben (5500) leads the IT group. The mixed chain puts the best-paid first within each department, and Ana and Zoe, tied at 6100, fall through to the third key, the name. compareByDescending does the same across the whole staff: [Ana, Zoe, Ben, Mia, Leo]. reversed() turns every key around, including the name tie-breaker, so Zoe now comes before Ana. To reverse only one key, chain it with thenByDescending instead.
3Nullable properties: nullsFirst and nullsLast
A key can be nullable, like a due date that isn't set yet. sortedBy accepts it without complaint and treats null as smaller than every value, so the nulls come first going up and last going down. To sort ascending with the nulls at the end, pass nullsLast() as the comparator for that key: compareBy(nullsLast()) { it.due }. nullsLast can wrap another comparator too, such as String.CASE_INSENSITIVE_ORDER. When the list itself holds null elements, wrap the whole comparator instead.
data class Task(val title: String, val due: Int?, val owner: String?) fun main() { val tasks = listOf( Task("Ship", 3, "ana"), Task("Plan", null, "Leo"), Task("Test", 1, null), Task("Docs", null, "bob"), Task("Fix", 2, "Ana"), ) // A nullable key: null counts as smaller than any value println(tasks.sortedBy { it.due }.map { it.title }) println(tasks.sortedByDescending { it.due }.map { it.title }) // Ascending, with the nulls at the end val dueFirst = tasks.sortedWith(compareBy(nullsLast()) { it.due }) println(dueFirst.map { it.title }) // Then a tie-breaker for the tasks with no date val dueThenTitle = compareBy<Task, Int?>(nullsLast()) { it.due } .thenBy { it.title } println(tasks.sortedWith(dueThenTitle).map { it.title }) // nullsLast can wrap another comparator: here, ignore case val byOwner = tasks.sortedWith( compareBy(nullsLast(String.CASE_INSENSITIVE_ORDER)) { it.owner }, ) println(byOwner.map { it.owner }) // A fallback value works too, when one makes sense println(tasks.sortedBy { it.due ?: Int.MAX_VALUE }.map { it.title }) // Null elements, not null keys: wrap the whole comparator val maybe: List<Task?> = listOf(tasks[0], null, tasks[4]) println(maybe.sortedWith(nullsLast(compareBy { it.due })).map { it?.title }) }
Output
Plain sortedBy puts the undated Plan and Docs first, and sortedByDescending puts them last. With nullsLast() the dated tasks run 1, 2, 3 (Test, Fix, Ship) and the undated ones follow; thenBy then orders those two by title, Docs before Plan. The owner sort ignores case, so ana and Ana sit together and the missing owner is last. The fallback key it.due ?: Int.MAX_VALUE gives the same order as nullsLast() here. In the chained version, compareBy<Task, Int?> names both the element type and the key type: with a comparator for the key, compareBy has two type parameters, and without an expected type Kotlin can't infer them from the lambda.
4Sort in place: sortBy vs sortedBy
The functions without -ed sort the collection itself: sortBy, sortByDescending, sortWith and sort. They exist only on MutableList and arrays, and they return Unit, not the list. This is the Kotlin form of Java's Collections.sort(list, comparator) and list.sort(comparator). On a read-only List the call doesn't compile: Unresolved reference 'sortBy' on receiver of type 'List<Int>'. Use sortedBy there, or make a mutable copy first.
data class Player(val name: String, val score: Int) fun main() { val players = mutableListOf( Player("Mia", 70), Player("Ana", 95), Player("Leo", 70), ) // sortedByDescending: a new list, players itself is untouched val ranked = players.sortedByDescending { it.score } println("ranked: ${ranked.map { it.name }}") println("players: ${players.map { it.name }}") // sortByDescending: sorts players itself players.sortByDescending { it.score } println("players: ${players.map { it.name }}") // It returns Unit, not the list val result = players.sortBy { it.name } println(result) println(players.map { it.name }) // sortWith takes a comparator, like sortedWith players.sortWith(compareBy({ it.score }, { it.name })) println(players.map { it.name }) // Arrays sort in place the same way val board = arrayOf(Player("Kai", 10), Player("Eve", 30)) board.sortByDescending { it.score } println(board.joinToString { it.name }) // A read-only List has no sortBy: copy it, or use sortedBy val fixed = listOf(Player("Zed", 1), Player("Amy", 2)) val copy = fixed.toMutableList() copy.sortBy { it.name } println("${fixed.map { it.name }} ${copy.map { it.name }}") }
Output
sortedByDescending leaves players as [Mia, Ana, Leo]; sortByDescending changes it to [Ana, Mia, Leo]. Printing the result of sortBy shows kotlin.Unit, a common slip when moving from sortedBy: the sorted data is in the list, not in the return value. sortWith orders by score, then name, giving [Leo, Mia, Ana]. The copy is sorted while fixed keeps [Zed, Amy]. Pick sortedBy by default; sort in place when you own a large mutable list and don't need the old order.
5A natural order: Comparable and compareValuesBy
When a type has one obvious order, such as version numbers, implement Comparable<Version> and write compareTo once. Then sorted(), sortedDescending(), max() and the < and > operators all work without a key. compareValuesBy(this, other, …) is the short way to compare several values in compareTo: it checks each lambda in turn and returns at the first difference, the same rule compareBy follows. A data class doesn't get an order for free; it has equals, not compareTo.
data class Version(val major: Int, val minor: Int, val patch: Int) : Comparable<Version> { // Compare major, then minor, then patch override fun compareTo(other: Version): Int = compareValuesBy(this, other, { it.major }, { it.minor }, { it.patch }) override fun toString() = "$major.$minor.$patch" } fun main() { val versions = listOf( Version(1, 10, 0), Version(1, 2, 5), Version(2, 0, 0), Version(1, 2, 10), ) // Comparable types sort with no key at all println(versions.sorted()) println(versions.sortedDescending()) println(versions.max()) // compareTo also powers < > and ranges println(Version(1, 2, 5) < Version(1, 10, 0)) println(Version(1, 2, 5) in Version(1, 0, 0)..Version(1, 9, 0)) // A different order for one call still works println(versions.sortedBy { it.patch }) // The same versions as strings sort character by character println(listOf("1.10.0", "1.2.5", "2.0.0", "1.2.10").sorted()) }
Output
sorted() gives [1.2.5, 1.2.10, 1.10.0, 2.0.0]: 10 is bigger than 2 as a number, so 1.10.0 comes after 1.2.10, and max() is 2.0.0. The same versions as strings sort to [1.10.0, 1.2.10, 1.2.5, 2.0.0], because the character 1 in 10 comes before 2. That is the usual reason to parse values into a class before sorting. sortedBy still overrides the natural order for one call; the ties at patch 0 keep their list order. If a class has no single natural order, skip Comparable and keep named comparators, for example in a companion object.
6Stable sorting and hand-written comparators
Kotlin's sorts are stable: elements with equal keys keep the order they had before. That means sorting by the minor key and then by the major key gives the same result as one compareBy with both, though the single comparator is clearer and sorts once. When no key function fits, write the comparison yourself with Comparator { a, b -> … }, returning a negative number, zero or a positive number. Return a.compareTo(b), not a - b: the subtraction overflows for large values and gives a wrong order without any error.
data class Order(val id: Int, val customer: String, val total: Int) fun main() { val orders = listOf( Order(1, "Leo", 30), Order(2, "Ana", 50), Order(3, "Leo", 20), Order(4, "Ana", 10), Order(5, "Mia", 50), ) // Stable: orders with the same customer keep their original order println(orders.sortedBy { it.customer }.map { it.id }) // Two passes, minor key first, equal one comparator with both keys val twoPasses = orders.sortedBy { it.total }.sortedBy { it.customer } val oneComparator = orders.sortedWith( compareBy({ it.customer }, { it.total }), ) println(twoPasses.map { it.id }) println(oneComparator.map { it.id }) // A hand-written comparator: negative, zero or positive val byTotalDesc = Comparator<Order> { a, b -> b.total.compareTo(a.total) } println(orders.sortedWith(byTotalDesc).map { it.id }) // Never compare by subtracting: it overflows val numbers = listOf(Int.MIN_VALUE, 5, Int.MAX_VALUE, -5) println(numbers.sortedWith { a, b -> a - b }) println(numbers.sortedWith { a, b -> a.compareTo(b) }) }
Output
Sorted by customer, Ana's orders stay 2, 4 and Leo's stay 1, 3, as in the input. The two-pass sort and the single comparator both give [4, 2, 3, 1, 5]. The descending comparator keeps orders 2 and 5, both 50, in their input order. The subtraction comparator returns [5, 2147483647, -2147483648, -5], which is not sorted at all: 5 - Int.MIN_VALUE wraps around to a negative number. With compareTo the order is right. Most of the time, compareBy saves you from writing the comparison at all.
7Which should you use?
| Method | Result | Keys | Best for |
|---|---|---|---|
| list.sortedBy { it.age } | New List | One, ascending | Most sorts by one property |
| list.sortedByDescending { it.age } | New List | One, descending | Largest or newest first |
| sortedWith(compareBy({ … }, { … })) | New List | Several, all ascending | Ties broken by a second field |
| compareBy { … }.thenByDescending { … } | Comparator | Several, mixed directions | Group ascending, rank descending |
| compareBy(nullsLast()) { it.due } | Comparator | Nullable key | Missing values at the end |
| list.sortBy { … }, sortWith(…) | Unit, list changed | Same as the -ed forms | MutableList or array you own |
| Comparable + sorted() | New List | Written once in compareTo | Types with one natural order |
| Comparator { a, b -> a - b } | Comparator | Overflows | Avoid: use compareTo or compareBy |
Frequently asked questions
What is the difference between sortBy and sortedBy in Kotlin?
sortedBy returns a new sorted list and leaves the original alone, so it works on any List. sortBy reorders a MutableList or an array in place and returns Unit, so println(list.sortBy { it.age }) prints kotlin.Unit. On a read-only List, sortBy does not compile: Unresolved reference 'sortBy' on receiver of type 'List<Int>'.
How do I sort by one field ascending and another descending?
Chain a comparator: list.sortedWith(compareBy<Employee> { it.dept }.thenByDescending { it.salary }). If the first key is the descending one, start with compareByDescending<Employee> { it.salary } and add thenBy for the rest. reversed() on a whole comparator flips every key, which is rarely what you want for mixed directions.
How do I implement compareTo with multiple values?
Use compareValuesBy(this, other, { it.major }, { it.minor }, { it.patch }) as the body of compareTo. It compares by each lambda in turn and returns at the first one that differs. The class must implement Comparable<YourType>; after that, sorted(), max() and the < operator use your order.
How do I sort strings or a String property case-insensitively?
For a list of strings, names.sortedWith(String.CASE_INSENSITIVE_ORDER); for a property, list.sortedBy { it.name.lowercase() } or sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.name }). Plain sorted() on listOf("bob", "Ana", "leo", "Mia") gives [Ana, Mia, bob, leo], because uppercase letters sort first; the case-insensitive versions give [Ana, bob, leo, Mia].
How do I sort by a date property?
LocalDate, LocalDateTime and Instant from java.time are Comparable, so list.sortedBy { it.due } sorts oldest first and sortedByDescending { it.due } newest first. Store dates as LocalDate rather than strings: a string like "1/15/2026" sorts character by character, not by date.
How do I sort in a custom order, such as by status?
An enum key sorts by declaration order, so sortedBy { it.status } follows the order the constants are written in. For any other order, list it and sort by position: val order = listOf(Status.IN_PROGRESS, Status.OPEN, Status.DONE), then sortedBy { order.indexOf(it.status) }. A value missing from the list gets index -1 and sorts first.
How do I sort a Map by its values?
A map has no order to sort, so sort its entries: stock.entries.sortedBy { it.value } gives a list such as [plums=1, pears=4, apples=9]. To get a map back, stock.toList().sortedByDescending { it.second }.toMap() builds a map that keeps the sorted order, here {apples=9, pears=4, plums=1}.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground