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?
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.
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 .
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With