kotlin-compare-objects-comparable-feature-image

Kotlin – Compare Objects & Sort List with Comparable Example

This tutorial shows you way to compare Objects, then sort List of Objects with Comparable by examples.

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


Overview

Goal

– First, we compare objects with type Date(year:Int, month:Int, day:Int).
– Second, we continue to compare objects by Date. The objects has type Product(name:String, date:Date).
– Finally, we sort List of Date objects, then sort List of Product objects.

Steps to do

– Implement Comparable interface for the class of objects you want to compare.
– Override compareTo(other: T) method and:
+ return zero if this object is equal other
+ a negative number if it’s less than other
+ a positive number if it’s greater than other

Practice

Create Classes

Let’s define two classes: Date and Product.
All of them will implement Comparable interface.

Date.kt

package com.bezkoder.kotlin.comparable

import kotlin.Comparable

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

	override fun compareTo(other: Date) = when {
		year != other.year -> year - other.year
		month != other.month -> month - other.month
		else -> day - other.day
	}
}

Product.kt

package com.bezkoder.kotlin.comparable

import kotlin.Comparable

data class Product(val name: String, val releasedDate: Date) : Comparable {

	override fun compareTo(other: Product) = when {
		releasedDate < other.releasedDate -> -1
		releasedDate > other.releasedDate -> 1
		else -> 0
	}
}

Because Product class includes Date field which implemented Comparable interface, so you can compare two Date objects inside using operator <,>,==.

Compare Objects

For comparing Date objects:

package com.bezkoder.kotlin.comparable

fun main(args: Array<String>) {
  val date1 = Date(2020, 7, 29)
  val date2 = Date(2021, 4, 3)
  val date3 = Date(2021, 2, 26)

  println(date1.toString() + " -- comes " + compDateResult(date1, date2) + " -- " + date2.toString())
  println(date2.toString() + " -- comes " + compDateResult(date2, date3) + " -- " + date3.toString())
}

fun compDateResult(d1: Date, d2: Date): String {
  return when {
    d1 < d2 -> "BEFORE"
    d1 > d2 -> "AFTER"
    else -> "AT THE SAME TIME AS"
  }
}

Result:

Date(year=2020, month=7, day=29) -- comes BEFORE -- Date(year=2021, month=4, day=3)
Date(year=2021, month=4, day=3) -- comes AFTER -- Date(year=2021, month=2, day=26)

For comparing Product objects:

package com.bezkoder.kotlin.comparable

fun main(args: Array<String>) {
  val product1 = Product("AAA", Date(2021, 4, 3))
  val product2 = Product("ZZZ", Date(2021, 2, 26))
  
  println(product1.toString() + " -- comes " + compProductResult(product1, product2) + " -- " + product2.toString())
}

fun compProductResult(p1: Product, p2: Product): String {
  return when {
    p1 < p2 -> "BEFORE"
    p1 > p2 -> "AFTER"
    else -> "AT THE SAME TIME AS"
  }
}

Result:

Product(name=AAA, releasedDate=Date(year=2021, month=4, day=3)) -- comes AFTER -- Product(name=ZZZ, releasedDate=Date(year=2021, month=2, day=26))

Sort List of Objects

Comparable also helps us to sort List of Objects. You can find more details at:
Kotlin – Sort List of custom Objects

For sorting List of Date objects:

package com.bezkoder.kotlin.comparable

fun main(args: Array<String>) {
  val dates = listOf(
    Date(2021, 4, 3),
    Date(2020, 7, 29),
    Date(2021, 2, 26)
  )

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

  println("--- DESC ---")
  dates.sortedDescending().forEach { println(it) }
}

Output:

--- ASC ---
Date(year=2020, month=7, day=29)
Date(year=2021, month=2, day=26)
Date(year=2021, month=4, day=3)
--- DESC ---
Date(year=2021, month=4, day=3)
Date(year=2021, month=2, day=26)
Date(year=2020, month=7, day=29)

Let’s sort List of Product objects:

package com.bezkoder.kotlin.comparable

fun main(args: Array<String>) {
  val products = listOf(
    Product("AAA", Date(2021, 4, 3)),
    Product("DDD", Date(2020, 7, 29)),
    Product("ZZZ", Date(2021, 2, 26))
  )
  
  println("--- ASC ---")
  products.sorted().forEach { println(it) }
  
  println("--- DESC ---")
  products.sortedDescending().forEach { println(it) }
}

Output:

--- ASC ---
Product(name=DDD, releasedDate=Date(year=2020, month=7, day=29))
Product(name=ZZZ, releasedDate=Date(year=2021, month=2, day=26))
Product(name=AAA, releasedDate=Date(year=2021, month=4, day=3))
--- DESC ---
Product(name=AAA, releasedDate=Date(year=2021, month=4, day=3))
Product(name=ZZZ, releasedDate=Date(year=2021, month=2, day=26))
Product(name=DDD, releasedDate=Date(year=2020, month=7, day=29))

Conclusion

Using Kotlin Comparable makes the comparing objects clean and easy to read because we can use relational Operators such as: <, <=, >, >=, ==.

And sorting List of Comparable objects is also convenient, directly to the list without the need of additional parameters.

Happly Learning! See you again.

10 thoughts to “Kotlin – Compare Objects & Sort List with Comparable Example”

  1. As a Kotlin developer, I believe the Kotlin tutorial here is excellent, appreciate it for your efforts. Keep it up forever! Good Luck.

Leave a Reply

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