binarySearchBy

inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size, crossinline selector: (T) -> K?): Int(source)

Searches this list or its range for an element having the key returned by the specified selector function equal to the provided key value using the binary search algorithm. The list is expected to be sorted into ascending order according to the Comparable natural ordering of keys of its elements. otherwise the result is undefined.

If the list contains multiple elements with the specified key, there is no guarantee which one will be found.

null value is considered to be less than any non-null value.

Since Kotlin

1.0

Return

the index of the element with the specified key, if it is contained in the list within the specified range; otherwise, the inverted insertion point (-insertion point - 1). The insertion point is defined as the index at which the element should be inserted, so that the list (or the specified subrange of list) still remains sorted.

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   data class Box(val value: Int)

val numbers = listOf(1, 3, 7, 10, 12)
val boxes = numbers.map { Box(it) }
println(boxes.binarySearchBy(10) { it.value }) // 3 
   //sampleEnd
}