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.

Download Code

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.

Download Code

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.