kotlin-comparator-feature-image

Kotlin Comparator & Sort List of objects example

In this tutorial, I will show you how to create Kotlin Comparator and custom Comparator, then we’re gonna use Comparator to sort List of objects.

Related Posts:
Kotlin – Sort List of custom Objects
Kotlin – Compare Objects with Comparable Example
Kotlin Priority Queue tutorial with examples


Kotlin Comparator

Kotlin provides Comparator interface to order the objects of user-defined classes.

There are two ways to create a Comparator object:

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

Comparator compareBy()

These are ways to create Comparator object for Date(year,month,day) class:

compareBy<Date> { it.year }.thenBy { it.month }.thenBy { it.day }
compareBy<Date>({ it.year }, { it.month }, { it.day })

Custom Comparator

We’re gonna follow these steps:
– Implement Comparator interface for the class that you use for handling sorting.
– Override compare(object1: T, object2: T) method and:

  • return zero if object1 is equal object2
  • a negative number if object1 is less than object2
  • a positive number if object1 is greater than object2

Sort List of objects using Comparator

Create Data Class for objects to be sorted

We’re gonna create a data class with 3 fields: year, month & day.

Date.kt

package com.bezkoder.kotlin.comparator

data class Date(val year: Int, val month: Int, val day: Int) {
}

Create Class for handling sorting

This is the main part, DateComparator class overrides Comparator.compare() method.

DateComparator.kt

package com.bezkoder.kotlin.comparator

class DateComparator {

	companion object : Comparator<Date> {

		override fun compare(a: Date, b: Date): Int = when {
			a.year != b.year -> a.year - b.year
			a.month != b.month -> a.month - b.month
			else -> a.day - b.day
		}
	}
}

Create test function

For checking our Comparator objects, we’re gonna create a List of Date objects and sort it using sortedWith() method.

app.kt

package com.bezkoder.kotlin.comparator

fun main(args: Array<String>) {
  val dates = mutableListOf(
    Date(2020, 4, 3),
    Date(2021, 5, 16),
    Date(2020, 1, 29)
  )
  
  println("--- ASC ---")
  dates.sortedWith(compareBy { it.year }.thenBy { it.month }.thenBy { it.day })
       .forEach { println(it) }
       
//  dates.sortedWith(compareBy({ it.year }, { it.month }, { it.day })).forEach { println(it) }

  println("--- DESC ---")
  dates.sortedWith(compareBy({ it.year }, { it.month }, { it.day }).reversed())
       .forEach { println(it) }

  println("--- ASC ---")
  dates.sortedWith(DateComparator).forEach { println(it) }

  println("--- DESC ---")
  dates.sortedWith(DateComparator).reversed().forEach { println(it) }
}

The Output in console will look like this:

--- ASC ---
Date(year=2020, month=1, day=29)
Date(year=2020, month=4, day=3)
Date(year=2021, month=5, day=16)
--- DESC ---
Date(year=2021, month=5, day=16)
Date(year=2020, month=4, day=3)
Date(year=2020, month=1, day=29)

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *