Kotlin: the most effective way to find first index of minimum element in some list of some objects

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

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
}

Tags:

Kotlin