Sort a List by multiple fields in Kotlin
This article explores different ways to sort a list by multiple fields in Kotlin.
1. Using sortWith() function
We can use Comparator to get control over the sort order and sort a list by multiple fields. A Comparator can be passed to the sortWith() function to define how two items in the list should be compared. Consider the following code which creates a List<Person> and in-place sort it based on the name. If two objects have the same name, the ordering is decided by their age.
There are several ways to construct a Comparator to sort a list by multiple fields. We can pass a method reference to the compareBy, which extracts and returns a Comparator based on that function. To sort on multiple fields, we can use thenBy() to combine two comparisons. To sort in descending order, use thenByDescending() instead.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Person(val name: String, val age: Int) { override fun toString(): String { return "Person(name='$name', age=$age)" } } fun main() { val persons = mutableListOf( Person("Olivia", 25), Person("George", 15), Person("Olivia", 20), Person("Harry", 10) ) persons.sortWith(compareBy({ it.name }, { it.age })) // or // persons.sortWith(compareBy(Person::name, Person::age)) // persons.sortWith(compareBy<Person> { it.name }.thenBy { it.age }) // persons.sortWith(compareBy<Person> { it.name }.thenByDescending { it.age }) for (person in persons) { println(person) } } |
Output:
Person(name='George', age=15)
Person(name='Harry', age=10)
Person(name='Olivia', age=20)
Person(name='Olivia', age=25)
2. Using sortedWith() function
To get a sorted list, without modifying the original list, use the sortedWith() function. It accepts a Comparator which can be used to sort a list by multiple fields, as with the sortWith() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Person(val name: String, val age: Int) { override fun toString(): String { return "Person(name='$name', age=$age)" } } fun main() { val persons = listOf( Person("Olivia", 25), Person("George", 15), Person("Olivia", 20), Person("Harry", 10) ) persons.sortedWith(compareBy({ it.name }, { it.age })).forEach(::println) // or // persons.sortedWith(compareBy(Person::name, Person::age)).forEach(::println) // persons.sortedWith(compareBy<Person> { it.name }.thenBy { it.age }).forEach(::println) // persons.sortedWith(compareBy<Person> { it.name }.thenByDescending { it.age }) // .forEach(::println) } |
Output:
Person(name='George', age=15)
Person(name='Harry', age=10)
Person(name='Olivia', age=20)
Person(name='Olivia', age=25)
That’s all about sorting a list by multiple fields in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)