Open In App

Sort a List by Specified Comparator in Kotlin

Last Updated : 20 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

As we all know Sorting a list is one of the most common operations done on the list so, in this article, we are going to discuss how to sort a list by the specified comparator in Kotlin. When we try to sort a list of custom objects, we need to specify the comparator. Let’s see how we can sort a list by the specified comparator.

Kotlin Comparator

Kotlin provides a Comparator interface to order the objects of user-defined classes. There are two ways to create a Comparator object:

  • using compareBy() (and thenBy() for comparing more fields)
  • creating custom Comparator

If you want to reverse the ordering of the Comparator (sort by Descending, for example), just use reversed().

Read more here: Comparator in Kotlin

Example

In the following examples, we will try to sort objects based on certain properties. This will give us an idea of how to sort based on the specified comparator. Let’s create a Person class with age property. We will be sorting a list of person objects based on age:

Kotlin




fun main (args: Array<String>){
  val p1=Person (91)
  val p2=Person (10)
  val p3=Person (78)
  val listOfPerson= listof (pl, p2, p3)
  var sortedListOfPerson=listOfPerson.sortedBy {
    it.age
  }
}
class Person (var age: Int)


To sort a list based on the specified comparator, we need to use the sortedBy function

Kotlin




fun main (args: Array<String>) {
  val p1=Person (91)
  val p2=Person (10
  val p3=Person (78)
  val listOfPerson = listOf (pl, p2, p3)
  var sortedListOfPerson = listOfPerson.sortedBy {
    it.age
  }
}
class Person (var age: Int)


Kotlin also provides a sortedwith method, where you can specify your own implementation of comparator:

Kotlin




fun main (args: Array<String>){
  val pi=Person (91)
  val p2=Person (10)
  val p3=Person (78)
  val listofPerson = listOf (pl, p2, p3)
  var sortedListOfperson = listofperson
    .sortedWith <Person> (object : Comparator <Person> {
      override fun compare (p0: Person, pi: Person) : Int {
        if (p0.age > pl.age) {
          return 1
        }
        if (p0.age = pl.age) {
          return 0
        
        return -1
      }
    })
}
class Person (var age: Int)


The sortedBy function is syntactic sugar provided by Kotlin. Internally, it’s called the sortedWith method that takes in a comparator. Now, let’s see the implementation of the sortBy function:

Kotlin




public inline fun <T, R : Comparable<R>> Iterable<T> . sortedBy (crossinline
                        selector: (T) -> R?) : List<T> {
  return sortedWith (compareBy (selector) )
}


The sortBy function calls the sortedwith method inside it, which is as follows:

Kotlin




public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>) :
List<T> {
  if (this is Collection) {
    if (size <= 1) return this.toList ()
    @Suppress ("UNCHECKED_CAST")
    return (toTypedArray<Any?> () as Array<T>).apply {
 sortWith (comparator) }.asList ()
  }
  return toMutableList ().apply { sortWith (comparator) }
}




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads