This tutorial shows you way to Sort List of Objects by implementing Comparator
example.
Related Post: Kotlin List & Mutable List tutorial with examples
>>> Refer to: Kotlin – Sort List of Objects with Kotlin Comparator Example
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
1 2 3 4 5 |
package com.kolination.objcomparator data class MyDate (val year: Int, val month: Int, val day: Int) { } |
2. Create Class for handling sorting
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.kolination.objcomparator class CompareObjects { companion object : Comparator<MyDate> { 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
1 2 3 4 5 6 7 8 |
package com.kolination.objcomparator fun main(args: Array<String>) { 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:
1 2 3 4 5 |
fun <T> compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator<T> { return object : Comparator<T> { public override fun compare(a: T, b: T): Int = compareValuesBy(a, b, *selectors) } } |
Calling sortedWith() method now becomes:
1 |
myDates.sortedWith(compareBy({ it.year }, { it.month }, { it.day })).forEach { println(it) } |
4. Run & check Result
1 2 3 4 |
=== Sort using Comparator === MyDate(year=2006, month=5, day=16) MyDate(year=2007, month=6, day=29) MyDate(year=2010, month=4, day=3) |