Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

327
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda