binarySearchBy

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(
    key: K?, 
    fromIndex: Int = 0, 
    toIndex: Int = size, 
    crossinline selector: (T) -> K?
): Int

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.

import kotlin.test.*

fun main(args: Array<String>) {
//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
}

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.

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/binary-search-by.html