Kotlin – Sort List of Objects with Comparable

This tutorial shows you way to Sort List of Objects by Kotlin Comparable example.

Related posts:
Kotlin – Compare Objects with Comparable Example
Kotlin – Sort List of Objects with Kotlin Comparator Example
Kotlin Sort Object List with Kotlin Selector function – crossinline selector: (T) -> R?

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Overview

1. Goal

Sort list of three Date(year,month,day) objects.

2. Steps to do

– Implement Comparable interface for the class of objects you want to sort.
– 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
– Use sorted() method that returns a List.

III. Practice

1. Create Class for objects to be sorted


package com.javasampleapproach.objcomparable

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
	}
}

2. Create test function


package com.javasampleapproach.objcomparable

fun main(args: Array) {

	println("=== Sort using Comparable ===")
	val dates = listOf(Date(2010, 4, 3), Date(2006, 5, 16), Date(2007, 6, 29))
	dates.sorted().forEach { println(it) }
}

3. Run & check Result


=== Sort using Comparable ===
Date(year=2006, month=5, day=16)
Date(year=2007, month=6, day=29)
Date(year=2010, month=4, day=3)


By grokonez | December 14, 2017.

Last updated on April 27, 2021.



Related Posts


Got Something To Say:

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

*