Kotlin List binarySearchBy()
Syntax & Examples
Syntax of List.binarySearchBy()
The syntax of List.binarySearchBy() extension function is:
fun <T, K : Comparable<K>> List<T>.binarySearchBy( key: K?, fromIndex: Int = 0, toIndex: Int = size, selector: (T) -> K? ): IntThis binarySearchBy() extension function of List 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.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining integers from 1 to 6. - We use the
binarySearchByfunction to find the index of an element with key 4 inlist. - The selector function
{ it }returns the element itself as the key. - The result, which is the index of the element with key 4 in
list, is stored inindex. - We print the index of the element with key 4 using
println.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5, 6)
val index = list.binarySearchBy(4) { it }
println("Index of element with key 4: \$index")
}Output
Index of element with key 4: 3
2 Example
In this example,
- We create a list named
listcontaining strings"apple", "banana", "cherry", "grape". - We use the
binarySearchByfunction to find the index of an element with key"cherry"inlist. - The selector function
{ it }returns the element itself as the key. - The result, which is the index of the element with key
"cherry"inlist, is stored inindex. - We print the index of the element with key
"cherry"usingprintln.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "grape")
val index = list.binarySearchBy("cherry") { it }
println("Index of element with key 'cherry': \$index")
}Output
Index of element with key 'cherry': 2
3 Example
In this example,
- We define a data class
Personwith propertiesnameandage. - We create a list named
listcontaining instances ofPerson. - We use the
binarySearchByfunction to find the index of an element with key 25 inlist, where the key is theageproperty of eachPersoninstance. - The result, which is the index of the element with age 25 in
list, is stored inindex. - We print the index of the element with age 25 using
println.
Kotlin Program
fun main(args: Array<String>) {
data class Person(val name: String, val age: Int)
val list = listOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val index = list.binarySearchBy(25) { it.age }
println("Index of element with age 25: \$index")
}Output
Index of element with age 25: 1
Summary
In this Kotlin tutorial, we learned about binarySearchBy() extension function of List: the syntax and few working examples with output and detailed explanation for each example.