How to sort an array in descending order using several comparison fields in Kotlin

Kotlin allows you to sort ASC and array using multiple comparison fields.

For instance:

return ArrayList(originalItems).sortedWith(compareBy({ it.localHits }, { it.title })) 

But when I try to sort DESC ( compareByDescending() ), it does not allow me to use multiple comparison fields.

Can I do this?

+5
source share
4 answers

You can use the extension function thenByDescending() (or thenBy() to increase) to define a secondary Comparator .

Assuming originalItems are SomeCustomObject , something like this should work:

 return ArrayList(originalItems) .sortedWith(compareByDescending<SomeCustomObject> { it.localHits } .thenByDescending { it.title }) 

(of course, you should replace SomeCustomObject with your own type for general)

+6
source

You can also just use sort ASC and then undo it:

 return ArrayList(originalItems).sortedWith(compareBy({ it.localHits }, { it.title })).asReversed() 

The implementation of asReversed() is a representation of a sorted list with a reverse index and has better performance than using reverse()

+1
source

Comparator reversal also works:

 originalItems.sortedWith(compareBy<Item>({ it.localHits }, { it.title }).reversed()) 
+1
source
 ArrayList(originalItems).sortedWith(Comparator { b, a -> compareValuesBy(a, b, { it.localHits }, { it.title }) }) 

Or you can define this function:

 fun <T> compareByDescending(vararg selectors: (T) -> Comparable<*>?): Comparator<T> { return Comparator { b, a -> compareValuesBy(a, b, *selectors) } } 

and use it as follows:

 ArrayList(originalItems).sortedWith(compareByDescending({ it.localHits }, { it.title })) 
+1
source

Source: https://habr.com/ru/post/1276214/


All Articles