Kirill Rakhman
Kirill Rakhman

Reputation: 43811

How to sort based on/compare multiple values in Kotlin?

Say I have a class Foo(val a: String, val b: Int, val c: Date) and I want to sort a list of Foos based on all three properties. How would I go about this?

Upvotes: 105

Views: 42656

Answers (3)

Yago Rey
Yago Rey

Reputation: 281

If you need sort by multiple fields, and some field by descending and others by ascending you could use:

YOUR_MUTABLE_LIST.sortedWith(compareBy<YOUR_OBJECT> { it.PARAM_1}.thenByDescending { it.PARAM_2}.thenBy { it.PARAM_3})

Upvotes: 2

CoolMind
CoolMind

Reputation: 28793

If you want to sort in descending order, you can use the accepted answer:

list.sortedWith(compareByDescending<Foo> { it.a }.thenByDescending { it.b }.thenByDescending { it.c })

Or create an extension function like compareBy:

/**
 * Similar to
 * public fun <T> compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator<T>
 *
 * but in descending order.
 */
public fun <T> compareByDescending(vararg selectors: (T) -> Comparable<*>?): Comparator<T> {
    require(selectors.size > 0)
    return Comparator { b, a -> compareValuesByImpl(a, b, selectors) }
}

private fun <T> compareValuesByImpl(a: T, b: T, selectors: Array<out (T) -> Comparable<*>?>): Int {
    for (fn in selectors) {
        val v1 = fn(a)
        val v2 = fn(b)
        val diff = compareValues(v1, v2)
        if (diff != 0) return diff
    }
    return 0
}

and use: list.sortedWith(compareByDescending ({ it.a }, { it.b }, { it.c })).

Upvotes: 1

Kirill Rakhman
Kirill Rakhman

Reputation: 43811

Kotlin's stdlib offers a number of useful helper methods for this.

First, you can define a comparator using the compareBy() method and pass it to the sortedWith() extension method to receive a sorted copy of the list:

val list: List<Foo> = ...
val sortedList = list.sortedWith(compareBy({ it.a }, { it.b }, { it.c }))

Second, you can let Foo implement Comparable<Foo> using the compareValuesBy() helper method:

class Foo(val a: String, val b: Int, val c: Date) : Comparable<Foo> {
    override fun compareTo(other: Foo)
            = compareValuesBy(this, other, { it.a }, { it.b }, { it.c })
}

Then you can call the sorted() extension method without parameters to receive a sorted copy of the list:

val sortedList = list.sorted()

Sorting direction

If you need to sort ascending on some values and descending on other values, the stdlib also offers functions for that:

list.sortedWith(compareBy<Foo> { it.a }.thenByDescending { it.b }.thenBy { it.c })

Performance considerations

The vararg version of compareValuesBy is not inlined in the bytecode meaning anonymous classes will be generated for the lambdas. However, if the lambdas themselves don't capture state, singleton instances will be used instead of instantiating the lambdas everytime.

As noted by Paul Woitaschek in the comments, comparing with multiple selectors will instantiate an array for the vararg call everytime. You can't optimize this by extracting the array as it will be copied on every call. What you can do, on the other hand, is extract the logic into a static comparator instance and reuse it:

class Foo(val a: String, val b: Int, val c: Date) : Comparable<Foo> {

    override fun compareTo(other: Foo) = comparator.compare(this, other)

    companion object {
        // using the method reference syntax as an alternative to lambdas
        val comparator = compareBy(Foo::a, Foo::b, Foo::c)
    }
}

Upvotes: 193

Related Questions