Kotlin Binary Search for Object List with Selector function – crossinline selector: (T) -> K?

In the tutorial, JavaSampleApproach will show you how to look up an element in an object list with Kotlin Binary Search for Object List by Selector function – selector: (T) -> R?.

Related posts:
Kotlin Sort Object List with Kotlin Selector function – crossinline selector: (T) -> R?
Kotlin Comparator Binary Search for Object List
Kotlin Comparable Binary Search for Object List
Kotlin Binary Search for Object List with Comparison function – comparison: (T) -> Int

I. Technologies

– Kotlin 1.1.61
– Java 8

II. Kotlin Binary Search with Selector function

Step to do:
– Create data model
– Create Selector function
– Create a sorted list
– Binary Search with Selector function

1. Create data model

– Create Product data model:

Initial Product list:

2. Create Selector function

We need define a selector function selector: (T) -> R?:

3. Create a sorted list

We can use Iterable.sortedBy(crossinline selector: (T) -> R?) to sort an Object List.
-> Detail method signature:

Sorting Product List:

More at: Kotlin Sort Object List with Kotlin Selector function – crossinline selector: (T) -> R?

4. Binary Search with Selector function

We use below method signature for Binary Search with Selector function:

Binary Search with Selector function will search in the ascending sorted list or its range for an element having the key returned by the specified [selector] function equal to the provided [key]. It will return the index of find out element. Otherwise, it will return the inverted insertion point (-insertion point – 1).

Note: The list is expected to be sorted into ascending order by the Comparable natural ordering of keys of its elements.

What is insertion point?
-> The insertion point is defined as the index at which an element with the given key should be inserted for the list (or specified range of list) still remains sorted.

III. Full Sourcecode

By JavaSampleApproach | December 16, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*