I have ChatMessage class like the code below:
class ChatMessage(val uid: String, val text: String, val fromId: String, val toId: String, val timestamp: Long) {}
it has timestamp as its property
I have an empty list like this, later I will populate this messageList with the data:
val messageList = ArrayList<ChatMessage>()
and I want to rearrange that messageList based on the timestamp, so the lowest timestamp will be in the index 0 of that array.
how to do that in Kotlin ? I am sorry if this is trivial, I am new in programming and in Kotlin.
You can use sorting function from Kotlin standard library.
Let's say, your messageList need to sort based on the timestamp then use following syntax below:
val sortedList :List<ChatMessage> = messageList.sortedBy { chatMessage :ChatMessage -> chatMessage.timestamp }
Above piece of code will return you sorted List<ChatMessage> which you can further use.
Find out more here.
You can use sortedWith with compareBy like this:
val sortedList = messageList.sortedWith(compareBy({ it.timestamp }))
You can even sort by multiple properties:
val sortedList = messageList.sortedWith(compareBy({ it.timestamp }, { it.fromId }))
Welcome to Kotlin
1) You can omit the curly braces for a class if they are empty, also your ChatMessage seems to be a good fit for a data class:
data class ChatMessage(val uid: String, val text: String, val fromId: String, val toId: String, val timestamp: Long)
2) You could create a container which you use to collect all messages in an ordered PriorityQueue, especially if you only need it ordered. This could look like this:
class MessageContainer {
private val messageList = PriorityQueue<ChatMessage>(Comparator { c1: ChatMessage, c2: ChatMessage ->
c1.timestamp.compareTo(c2.timestamp)
})
fun addMessage(msg: ChatMessage) = messageList.offer(msg)
fun getAllMessages(): List<ChatMessage> {
val ordered = mutableListOf<ChatMessage>()
while (!messageList.isEmpty()) ordered.add(messageList.remove())
return ordered.toList()
}
}
Now if you insert objects of ChatMessage via addMessage, they will be ordered in the queue directly and when you invoke getAllMessages, you receive an ordered List<ChatMessage>:
val container = MessageContainer()
repeat(20) {
container.addMessage(ChatMessage("text$it", (10L..10_000L).random()))
}
container.getAllMessages() //will be ordered