Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

335
Visualizações
how to rearrange order of ArrayList in Kotlin based on property of the object?

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.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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 }))
over 4 years ago · Santiago Trujillo Relatório

0

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
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda