Home > Software design >  SortBy nested non-comparable object with comparator
SortBy nested non-comparable object with comparator

Time:02-12

Suppose I have

data class NonComparable(val a : Any) //i.e. does not implement Comparable
data class WrappingElement(val nc : NonComparable)
val unordered = listOf<NonComparable>(....)
val comparator = Comparator<NonComparable>(){...}

What is the cleanest (least lines of code) way of sorting unordered with comparator?

In other words: How to reuse the logic in comparator (for NonComparable) to order a list of WrappingElements?

CodePudding user response:

Given you have a custom Comparator you want to reuse, like below:

object NonComparableComparator: Comparator<NonComparable> {
    override fun compare(p0: NonComparable, p1: NonComparable): Int {
        // your custom comparision logic here ...
    }
}

val comparator = NonComparableComparator

There is nothing stopping you to re-use this comparator in a Comparator for the wrapping element.

val wrappingElementComparator = Comparator<WrappingElement> {
        p0, p1 -> comparator.compare(p0.nonComparable, p1.nonComparable)
}

val sortedList = unsortedList.sortedWith(wrappingElementComparator)

All code above is based on the following:

data class NonComparable(val value: Any?)
data class WrappingElement(val nonComparable: NonComparable)

val unsortedList = listOf(
    WrappingElement(NonComparable(3)),
    WrappingElement(NonComparable(2)),
    WrappingElement(NonComparable(4)),
    WrappingElement(NonComparable(5)),
    WrappingElement(NonComparable(0)),
    WrappingElement(NonComparable(1)),
)
  • Related