This tutorial shows you way to Sort List of Objects by Kotlin Comparable
example.
Related Post: Kotlin List & Mutable List tutorial with examples
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
1 2 3 4 5 6 7 8 9 10 |
package com.kolination.objcomparable data class Date(val year: Int, val month: Int, val day: Int) : Comparable<Date> { 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
1 2 3 4 5 6 7 8 |
package com.kolination.objcomparable fun main(args: Array<String>) { 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
1 2 3 4 |
=== Sort using Comparable === Date(year=2006, month=5, day=16) Date(year=2007, month=6, day=29) Date(year=2010, month=4, day=3) |