DEV Community

loizenai
loizenai

Posted on

Kotlin Comparator Binary Search for Object List

https://grokonez.com/kotlin/kotlin-comparator-binary-search-object-list

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:

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:

data class Product(val name: String, val price: Double /*USD*/)
  • Create a Comparator:

class CompareObjects {
    companion object : Comparator {
        override fun compare(p1: Product, p2: Product): Int = (p1.price - p2.price).toInt()
    }
}

2. Create a sorted list

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

public fun  Iterable.sortedWith(comparator: Comparator): List

https://grokonez.com/kotlin/kotlin-comparator-binary-search-object-list

Kotlin Comparator Binary Search for Object List

Top comments (0)