Kotlin – Sort List of Objects with Kotlin Comparator Example

This tutorial shows you way to Sort List of Objects by implementing Comparator example.

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

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Overview

1. Goal

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

2. Steps to do

– 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
– Use sortedWith(comparator: Comparator) method that returns a List.

III. Practice

1. Create Class for objects to be sorted


package com.javasampleapproach.objcomparator

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

2. Create Class for handling sorting


package com.javasampleapproach.objcomparator

class CompareObjects {

	companion object : Comparator {

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

3. Create test function


package com.javasampleapproach.objcomparator

fun main(args: Array) {
	
	println("=== Sort using Comparator ===")
	val myDates = listOf(MyDate(2010, 4, 3), MyDate(2006, 5, 16), MyDate(2007, 6, 29))
	myDates.sortedWith(CompareObjects).forEach { println(it) }
}

We can also use fast way of creating Comparator with compareBy method:


fun  compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator {
    return object : Comparator {
        public override fun compare(a: T, b: T): Int = compareValuesBy(a, b, *selectors)
    }
}

Calling sortedWith() method now becomes:


myDates.sortedWith(compareBy({ it.year }, { it.month }, { it.day })).forEach { println(it) }

4. Run & check Result


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


By grokonez | August 29, 2017.

Last updated on April 17, 2021.



Related Posts


Got Something To Say:

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

*