1. Introduction
When you sort a list of numbers, everything is simple: the number itself is the value we compare by. But real life quickly gives you more complex data: “category–amount”, “name–points”, “product–price”, “purchase–cost–comment”. Elements no longer “ask” to be compared directly, and we need to decide: what exactly we are sorting by.
This “what” is called the sorting key: we take an element, compute a comparable value (a key) from it, and sort by that key. Kotlin provides very convenient tools for this: sortedBy and sortedByDescending.
Imagine you have a box of parcels, and each parcel has a sticker saying “weight”. You can sort the boxes (list elements), but it’s more convenient to compare by the sticker (the key). If the sticker is weight, sort by weight; if the sticker is city, sort by city.
2. Sort by key with sortedBy and sortedByDescending
Let’s start with the most common scenario: we have a list whose elements are not necessarily “comparable on their own”, but from each element we can extract something comparable (a number, a string, a string length). The Kotlin operation sortedBy { selector } takes a key selector function and returns a new list sorted in ascending order by that key.
Ascending sort: sortedBy {...}
First, a mini example without our project, just to see the mechanics. We sort strings by length (key is it.length):
fun main() {
val words = listOf("bbb", "a", "cc")
val sorted = words.sortedBy { it.length }
println(sorted) // [a, cc, bbb]
}
Now let’s bring this into a practical application. Reminder: the data model of our current console expense tracker (for now without classes) is: an expense is Triple(category, amount, note). Category and note are strings; amount is an Int.
Sorting all expenses by amount (ascending) looks like this:
fun main() {
val expenses = listOf(
Triple("food", 450, "coffee"),
Triple("taxi", 1200, "airport"),
Triple("food", 150, "snack")
)
val sortedByAmount = expenses.sortedBy { it.second }
println(sortedByAmount)
// [(food, 150, snack), (food, 450, coffee), (taxi, 1200, airport)]
}
Here it’s important to “read” the code correctly: we are sorting the Triple elements themselves, but comparing them by the key it.second, i.e., by the amount.
Descending sort: sortedByDescending {...}
A slightly more “practical” variant is sorting in descending order: in reports we almost always want to see the biggest first. For this there is sortedByDescending { selector }. It’s the same sorting-key principle, just with the reverse order.
For example, we want to show the most expensive purchases at the top:
fun main() {
val expenses = listOf(
Triple("food", 450, "coffee"),
Triple("taxi", 1200, "airport"),
Triple("books", 700, "kotlin book")
)
val sorted = expenses.sortedByDescending { it.second }
println(sorted)
// [(taxi, 1200, airport), (books, 700, kotlin book), (food, 450, coffee)]
}
And here the next step suggests itself: “can we take not the whole list, but only the first N?”. Yes — and that will be our classic top‑N pattern.
3. Top‑N: sortedByDescending {...}.take(n) and why take without sorting is not top
When requirements say “show the top‑3 categories”, it almost always means: sort by the metric and take the first three. Kotlin lets you express this as a single chain: sortedByDescending(...).take(n).
It’s important not to confuse it: take(n) does not search for the best elements; it simply takes the first n elements of the current order. So “taking top‑N” without sorting is literally “taking the first N in whatever order”.
First, a simple example with numbers:
fun main() {
val scores = listOf(10, 70, 50, 20, 90)
val top3 = scores.sortedDescending().take(3)
println(top3) // [90, 70, 50]
}
Now let’s make a top‑2 of the most expensive expenses in our Triple format:
fun main() {
val expenses = listOf(
Triple("food", 450, "coffee"),
Triple("taxi", 1200, "airport"),
Triple("books", 700, "kotlin book"),
Triple("food", 150, "snack")
)
val top2 = expenses
.sortedByDescending { it.second }
.take(2)
println(top2)
// [(taxi, 1200, airport), (books, 700, kotlin book)]
}
Notice a nice detail: if there are fewer elements than n, take(n) will simply return “as many as exist”, without crashes or drama.
4. Multiple criteria: sortedWith and compareBy
One of the most common “everyday” tasks is sorting by multiple rules. For example, we want to sort a list of pairs (category, total) so that categories come first by name (for pretty output), and if the name is the same, then the second key is amount or age.
Sorting by multiple criteria is like sorting documents in a folder: first by “Last name”, and within the same last name — by “First name”, and within the same first name — by “Date”. One criterion stops being enough.
In Kotlin, for cases where “you need to define an explicit comparison rule” there is sortedWith(comparator), and to avoid writing the comparator by hand there is a comparator factory compareBy(...). The standard approach looks like: sortedWith(compareBy {...}).
sortedWith(comparator): sort by an explicit rule
sortedWith(...) takes a Comparator<T> object and returns a new sorted list. This is useful when:
- the element is not Comparable,
- you have multiple criteria,
- you have tricky comparison logic (for example, “VIP first, then by amount”).
First, a simpler example: sort strings by length using a comparator:
fun main() {
val words = listOf("aaa", "bb", "c")
val sorted = words.sortedWith(compareBy { it.length })
println(sorted) // [c, bb, aaa]
}
Technically this is similar to sortedBy { it.length }, but the idea is different: we explicitly say “here is the comparison rule”. This is especially convenient when there are several criteria.
compareBy(...): comparator by a single key
compareBy is a way to say: “build me a comparator that compares elements by these keys”. We’re not diving into how a comparator works; we just use it as a ready-made tool.
For example, we sort our expenses (Triple) by category (alphabetically):
fun main() {
val expenses = listOf(
Triple("taxi", 1200, "airport"),
Triple("food", 450, "coffee"),
Triple("books", 700, "kotlin book")
)
val sorted = expenses.sortedWith(compareBy { it.first })
println(sorted)
// [(books, 700, kotlin book), (food, 450, coffee), (taxi, 1200, airport)]
}
compareBy({ ... }, { ... }): comparator by multiple keys
compareBy can take multiple selectors, and then sorting works like this: first by the first key; if equal — by the second; and so on.
Let’s make an example with pairs (category, total) and sort first by category name, and then by amount (ascending):
fun main() {
val totals = listOf(
"food" to 200,
"taxi" to 250,
"food" to 150
)
val sorted = totals.sortedWith(
compareBy<Pair<String, Int>>({ it.first }, { it.second })
)
println(sorted) // [(food, 150), (food, 200), (taxi, 250)]
}
Here I specified the type Pair<String, Int> explicitly to make it easier for the compiler (and for the reader). If you’re not yet confident with type inference, don’t hesitate to write types: it’s not a “weakness”, it’s insurance against mysterious errors that at 23:00 feel like magic.
5. Mini integration: top‑N category report by amount
Now let’s assemble a mini scenario that is very close to a real feature in an expense tracker: we have a Map<String, Int> with totals by category, and we want to output the top‑N categories by amount.
We are not using groupBy (that will come later), so let’s assume totalsByCategory has already been computed earlier by our code (for example, in the handler for the total command). Next is pure sorting mechanics.
Pipeline scheme:
Map<String, Int>
→ entries
→ List<Pair<String, Int>>
→ sortedByDescending { amount }
→ take(n)
→ print
Code (we’ll split into small steps so it reads like a human wrote it):
fun main() {
val totalsByCategory = mapOf(
"food" to 1200,
"taxi" to 2500,
"books" to 900
)
val topN = 2
val pairs = totalsByCategory.entries.map { it.key to it.value }
val top = pairs.sortedByDescending { it.second }.take(topN)
println(top) // [(taxi, 2500), (food, 1200)]
}
Two things are especially important here.
First, we don’t sort the Map directly, but its elements converted into a list of pairs. This is normal practice: sorting is an operation on a sequence (a list), while a Map itself is about “access by key”.
Second, top‑N is done strictly in this order: first sort, then take the first n. If you swap them, you’ll get “the first N by the internal Map order”, which is almost never a top (except for random coincidences that later break trust in the program).
6. How to choose the tool and read sortedBy
At some point students start asking: 「What’s better — sortedBy or sortedWith(compareBy(...))?」. It’s a fair question: both options often look similar.
Below is a small table to reinforce the choice:
| Task | What to write | Why |
|---|---|---|
| One simple key, ascending | |
The shortest and most readable option. |
| One simple key, descending | |
Same principle, just “biggest first”. |
| Multiple criteria | |
Clearly shows the set of criteria and the order they are applied. |
| Non-standard comparison rule | |
When you need to describe the comparison logic manually. |
And a small “human rule”: if you have one key — use sortedBy. If you have multiple criteria — in most cases sortedWith(compareBy(...)) reads better and scales more calmly.
Before the finish, let’s explicitly say the typical confusion. In sortedBy {...}, inside the lambda it is the list element, and the lambda result is the sorting key.
An example where people often get confused (because Pair is already short):
fun main() {
val totals = listOf("food" to 1200, "taxi" to 2500)
val sorted = totals.sortedBy { it.second }
println(sorted) // [(food, 1200), (taxi, 2500)]
}
it is a pair (String, Int). it.second is an Int, the sorting key. We sort the pairs, but compare the numbers.
If you catch yourself thinking 「Why am I sorting an Int if I have a list of pairs?」 — congratulations: you just noticed the sorting key, which means your brain is doing everything right.
7. Common mistakes
Mistake #1: using take(n) without sorting and calling it “top‑N”.
take(n) is not “select the best”; it’s “cut off the first n”. If the original order is insertion order, you’ll get “the first added”, not “the largest”. The fix is almost always the same: first sort by the metric, then take.
Mistake #2: sorting by the wrong key and mixing up first/second/third.
When data is stored in a Pair/Triple, it’s very easy to sort by the wrong field and spend a few minutes staring at the result feeling like the program is “messing with you”. A habit that helps: before sorting, name the meaning of fields in your head (“first=category, second=amount”), and in code sometimes temporarily print a couple of elements to verify.
Mistake #3: trying to sort a Map “as is”, and then being surprised.
Map is not a list; its main meaning is access by key, not order. For sorting you almost always need to do entries.map { ... }, get a list, and then sort that list. This is not a hack; it’s a normal container transformation for the task.
Mistake #4: trying to cram multiple criteria into one “monstrous” lambda.
When there are two or three criteria, beginners sometimes write a huge sortedWith { a, b -> ... }, where comparisons are mixed up, parentheses live their own life, and it all looks like a spell. In most cases it’s more readable and safer to use sortedWith(compareBy({ ... }, { ... })), where it’s immediately clear in what order the keys are applied.
Mistake #5: “losing” the sort result.
Sorts like sortedBy and sortedWith return a new list and do not change the original. If you write expenses.sortedBy { it.second } and then print expenses, nothing “magical” happened. The fix is simple: save it into a val or continue the chain immediately (for example, sortedByDescending { ... }.take(3)), as we did above.
GO TO FULL VERSION