This article explores different ways to sort a list of objects against multiple fields in Kotlin.

1. Using sortBy() function

The recommended solution to sort a list of objects is using the sortBy() function. The following example demonstrates this by sorting a list of Movie objects by their release year.

Download Code

Output:

Movie(name=Logan, year=2017)
Movie(name=Aquaman, year=2018)
Movie(name=Joker, year=2019)
Movie(name=Irishman, year=2019)

 
Note that the sortBy() function sorts the list only with a single field. If that field has the same value for two objects in the list, their relative ordering in the sorted list is not fixed. Therefore, it is preferred to compare objects using multiple fields.

2. Using sort() function

To sort a list of objects against the multiple fields, the class can implement the Comparable interface and override its abstract function compareTo() to define the position of an object relative to another object.

The following example demonstrates this by sorting a list of Movie objects using the sort() function, first by its release year and then by its name.

Download Code

Output:

Movie(name=Logan, year=2017)
Movie(name=Aquaman, year=2018)
Movie(name=Irishman, year=2019)
Movie(name=Joker, year=2019)

3. Using sortWith() function

You can also use the sortWith() function to sort a list according to the order specified by the given comparator. The returned value decides the position of the first object relative to the second object.

The following example uses the Comparator object to compare two Movie objects, first by their release year and then by their name.

Download Code

Output:

Movie(name=Logan, year=2017)
Movie(name=Aquaman, year=2018)
Movie(name=Irishman, year=2019)
Movie(name=Joker, year=2019)

 
Alternatively, you can use the Comparator.thenComparing() function, which effectively combines multiple Comparators into one:

Download Code

Output:

Movie(name=Logan, year=2017)
Movie(name=Aquaman, year=2018)
Movie(name=Irishman, year=2019)
Movie(name=Joker, year=2019)

That’s all about sorting a list of objects in Kotlin.