sortedBy and sortedWith
- Kotlin course
- Intermediate
- Lesson 67/116
- 5 min
Learn sorting with sortedBy and sortedWith.
sortedBy and sortedWith
sortedBy sorts ascending by a selector field and returns a new list. Example: people.sortedBy { it.age } orders ages from small to large. The original list is unchanged; the result is a separate list.
sortedWith takes a Comparator and enables more complex sorting. With compareBy you can define multiple fields: people.sortedWith(compareBy({ it.name }, { it.age })). For descending order use reverse() or sortedByDescending.
sortedWith and compareBy
Use sortedWith when sorting by multiple fields. The compareBy function evaluates sort keys in order: if the first field ties it looks at the second. Example: people.sortedWith(compareBy({ it.team }, { it.name })) sorts by team then by name.
For descending order use compareByDescending or reverseOrder() which returns a Comparator. Use sortedBy for a single simple field and sortedWith for multiple fields or custom comparison. Sorting is stable: equal elements keep their previous order.
Practice Apply sortedBy and sortedWith
Define data class Person(val name: String, val age: Int). Create listOf(Person("Alex", 30), Person("Sam", 20), Person("Mara", 25)). Sort by age with sortedBy { it.age } and print each with forEach { println(it) }. Then sort by name with sortedWith(compareBy { it.name }).
Starter code
data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(Person("Alex", 30), Person("Sam", 20), Person("Mara", 25))
// Sort by age with sortedBy, print with forEach; sort by name with sortedWith
}Sample solution
data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(Person("Alex", 30), Person("Sam", 20), Person("Mara", 25))
val byAge = people.sortedBy { it.age }
byAge.forEach { println(it) }
val byName = people.sortedWith(compareBy { it.name })
}Expected output
Person(name=Sam, age=20) Person(name=Mara, age=25) Person(name=Alex, age=30)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does sortedBy return?
- Modifies the original
- Does not sort
- A new sorted list Correct answer
- A reversed list
Explanation: sortedBy produces a new sorted list.
2 Complete the sortedBy call
people.____ { it.age }
people.sortedBy { it.age }
Explanation: answer: sortedBy. sortedBy sorts by one field.
3 Match the sorting expressions
| Term | Meaning |
|---|---|
sortedBy |
Single field |
sortedWith |
Takes Comparator |
compareBy |
Field order |
descending() |
Descending |