![]() |
VOOZH | about |
Sorting a list is one of the most common operations we perform when working with collections. In this article, we’ll learn how to sort a list by a specified comparator in Kotlin especially when the list contains objects of a custom class.
In Kotlin, a Comparator is an interface that helps us define how objects should be ordered. It tells Kotlin which property or rule to follow when sorting objects. For example, if we have a list of Person objects, and we want to sort them by their age, the comparator will help us do that. There are two ways to create a Comparator object:
If we want to sort in the opposite (descending) order, we can also use the reversed() function on the comparator.
Read more here: Comparator in Kotlin
Let’s understand this better with an example. Suppose we have a simple Person class with two properties: name and age.
data class Person(val name: String, val age: Int)Now we will sort a list of Person objects using different ways.
We can use the sortedBy() function to sort the list based on a specific property. For example, age.
Example:
Output:
[Person(name=Bob, age=20), Person(name=Alice, age=25), Person(name=Charlie, age=30)]In this example, the list is sorted in ascending order by age.
We can also create our own custom comparator using Comparator.
Example:
Output:
[Person(name=Bob, age=20), Person(name=Alice, age=25), Person(name=Charlie, age=30)]This way, we define exactly how two Person objects should be compared.
To sort in descending order, we can simply use reversed() on the comparator.
Example:
Output:
[Person(name=Charlie, age=30), Person(name=Alice, age=25), Person(name=Bob, age=20)]What if two people have the same age, and we want to sort them by name as a tie-breaker. We can use compareBy() with thenBy().
Example:
Output:
[Person(name=Bob, age=20), Person(name=Alice, age=25), Person(name=Charlie, age=30)]This first sorts by age, and then by name if the ages are the same.
Under the hood, sortedBy() uses the sortedWith() method along with a comparator.
When we write:
people.sortedBy { it.age }It actually does this internally:
people.sortedWith(compareBy { it.age })This is why sortedBy() is often called syntactic sugar, because it makes the code cleaner and easier to read, but does the same thing.