Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort in descending order using multiple comparison fields in Kotlin

Tags:

kotlin

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

For example:

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

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

Is there any way I can do it?

like image 814
Augusto Carmo Avatar asked Apr 02 '18 13:04

Augusto Carmo


People also ask

How does Kotlin sort in descending order?

To sort an Array in descending order in Kotlin, use Array. sortDescending() method. This method sorts the calling array in descending order in-place. To return the sorted array and not modify the original array, use Array.

How do I sort an Arraylist in Kotlin?

For sorting the list with the property, we use list 's sortedWith() method. The sortedWith() method takes a comparator compareBy that compares customProperty of each object and sorts it. The sorted list is then stored in the variable sortedList .


2 Answers

You could use the thenByDescending() (or thenBy() for ascending order) extension function to define a secondary Comparator.

Assuming originalItems are of SomeCustomObject, something like this should work:

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

(of course you have to replace SomeCustomObject with your own type for the generic)

like image 68
earthw0rmjim Avatar answered Sep 19 '22 14:09

earthw0rmjim


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

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

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

like image 42
leonardkraemer Avatar answered Sep 18 '22 14:09

leonardkraemer