Sorting data with custom comparators
In this recipe, we are going to explore the support for sorting collections' elements by their properties.
Getting started
Let's assume we are dealing with the two collections of the Message
type declared as follows:
data class Message(val text: String, val sender: String, val receiver: String, val time: Instant = Instant.now())
These are provided by the allMessages
variable:
val sentMessages = listOf(
Message("I'm programming in Kotlin, of course",
"Samuel",
"Agat",
Instant.parse("2018-12-18T10:13:35Z")),
Message("Sure!",
"Samuel",
"Agat",
Instant.parse("2018-12-18T10:15:35Z"))
)
val inboxMessages = mutableListOf(
Message("Hey Sam, any plans for the evening?",
"Samuel",
"Agat",
Instant.parse("2018-12-18T10:12:35Z")),
Message("That's cool, can I join you?",
"Samuel",
"Agat",
Instant.parse("2018-12-18T10:14:35Z"))
)
val allMessages = sentMessages + inboxMessages
If we print the...