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.
indexOf() to Check if Element is in List. If the element is present in the list, then list. indexOf(element), will return a non-negative integer, else it returns -1. We can use this behavior to check if element is present in the list or not.
The example presents Kotlin Set indexing operations. An element is retrieved with the elementAt method. The method takes an index of the element to be retrieved as a parameter. The indexOf returns the index of the first occurrence of the word in the set.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With