Kotlin Comparator Binary Search for Object List

In the tutorial, JavaSampleApproach will show you how to look up an element in an object list with Kotlin Comparator Binary Search.

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

I. Technologies

– Kotlin 1.1.61
– Java 8

II. Kotlin Comparator Binary Search

Step to do:
– Create data model & Comparator
– Create a sorted list
– Do Binary Search

1. Create data model & Comparator

– Create Product data model:

– Create a Comparator:

2. Create a sorted list

We can use Iterable.sortedWith(comparator: Comparator) to sort an Object List.
-> Detail method signature:

More at: Kotlin – Sort List of Objects with Kotlin Comparator Example

3. Comparator Binary Search

We use below method signature for Comparator Binary Search:

The Comparable Binary Search will search the sorted list or its range for the provided element using the binary search algorithm.
It will return the index of given element. Otherwise, it will return the inverted insertion point (-insertion point – 1).

Note: The list is expected to be sorted into ascending order according to the specified [comparator]

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

III. Full Sourcecode



By grokonez | December 15, 2017.


Related Posts


Got Something To Say:

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

*