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

380
Visualizações
Kotlin: the most effective way to find first index of minimum element in some list of some objects

I have some list of instances of some custom class:

data class Flight(val duration: Int)

For example:

val flights = listOf(Flight(10), Flight(5), Flight(5), Flight(15), Flight(20))

How to most effectively find first index of the minimum element in this list? In that case the first index of min element is 1, because flights[1].duration = 5.

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

0

Something like this would be "most efficient", I guess:

var min: Pair<Int, Flight>? = null
for (f in flights.withIndex()) {
    if (min == null || min.second.duration > f.value.duration) min = f.index to f.value
}

And this one does basically the same and looks much better:

flights.withIndex().minBy { (_, f) -> f.duration }?.index
over 4 years ago · Santiago Trujillo Relatório

0

With minBy() to get the list item with the minimum duration
and then indexOf() to get its index:

val index = flights.indexOf(flights.minBy { it.duration })

For just 1 scan of the list, you can do a classic loop:

var index = if (flights.isEmpty()) -1 else 0
flights.forEachIndexed { i, flight ->
    if (flight.duration < flights[index].duration) index = i
}
over 4 years ago · Santiago Trujillo Relatório

0

Try

val index = flights.minBy { it.duration }?.let { flights.indexOf(it) }
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