如何在Kotlin中使用多个比较字段按降序排序 [英] How to sort in descending order using multiple comparison fields in Kotlin
问题描述
Kotlin允许我使用多个比较字段对ASC和数组进行排序.
Kotlin allows me to sort ASC and array using multiple comparison fields.
例如:
return ArrayList(originalItems)
.sortedWith(compareBy({ it.localHits }, { it.title }))
但是当我尝试对DESC(compareByDescending()
)进行排序时,它不允许我使用多个比较字段.
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?
推荐答案
您可以使用thenByDescending()
(或thenBy()
升序)扩展功能来定义辅助Comparator
.
You could use the thenByDescending()
(or thenBy()
for ascending order) extension function to define a secondary Comparator
.
假设originalItems
是SomeCustomObject
,则类似这样的方法应该起作用:
Assuming originalItems
are of SomeCustomObject
, something like this should work:
return ArrayList(originalItems)
.sortedWith(compareByDescending<SomeCustomObject> { it.localHits }
.thenByDescending { it.title })
(当然,您必须用自己的通用类型替换SomeCustomObject
)
(of course you have to replace SomeCustomObject
with your own type for the generic)
这篇关于如何在Kotlin中使用多个比较字段按降序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!