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

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

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 Denunciar

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 Denunciar

0

Try

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