kotlin sorting objects code example
Example 1: sort object list kotlin
val dates = mutableListOf(
Date(2020, 4, 3),
Date(2021, 5, 16),
Date(2020, 1, 29)
)
println("--- ASC ---")
dates.sortWith(compareBy<Date> { it.year }.thenBy { it.month }.thenBy { it.day })
dates.forEach { println(it) }
Example 2: sort custom object list in kotlin
val messages = mutableListOf<Message>(
Message(from = "Tonnie", messageString = "Hi", timestamp = Date()),
Message(from = "Victoria", messageString = "Miss You", timestamp = Date()))
messages.sortWith(compareBy { it.timestamp })