This article explores different ways to sort an array of objects against the multiple fields in Kotlin.

1. Using sort() function

To sort an array of objects with the sort() function, the class should implement the Comparable interface and override its abstract function compareTo(), which decides the position of an object relative to another object. If compareTo() returns a

  • < 0, the object is less than the specified object.
  • = 0, the object is equal to the specified object.
  • > 0, the object is greater than the specified object.

 
The following example demonstrates this by sorting an array of Associate objects first by its age field and then by the name field.

Download Code

Output:

Associate(name=Joey, age=10)
Associate(name=John, age=15)
Associate(name=David, age=20)
Associate(name=Samuel, age=20)

2. Using sortWith() function

You can also use the sortWith() function, which sorts the array according to the order specified by the given comparator. The returned value decides the position of the first object relative to the second object.

  • < 0, the first argument is less than the second.
  • = 0, the first argument is equal to the second.
  • > 0, the first argument is greater than the second.

 
In the following example, the Comparator object compares Associate objects first by their age, followed by the name.

Download Code

Output:

Associate(name=Joey, age=10)
Associate(name=John, age=15)
Associate(name=David, age=20)
Associate(name=Samuel, age=20)

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

Download Code

Output:

Associate(name=Joey, age=10)
Associate(name=John, age=15)
Associate(name=David, age=20)
Associate(name=Samuel, age=20)

3. Using sortBy() function

A simple and fairly efficient solution is to sort an array of objects when comparisons are made on a single field using the sortBy() function.

Download Code

Output:

Associate(name=David, age=20)
Associate(name=Joey, age=10)
Associate(name=John, age=15)
Associate(name=Samuel, age=20)

That’s all about sorting an array of objects in Kotlin.