How to change the order of compareBy in Kotlin


#1

I need a comparator, in Kotlin, to order every object that enter in my recycler view (using Fast Adapter).

I need to order the objects by an Integer, where the biggest ones come first.

The code above order the object that enters in my list, but the biggest ones is in the end of the list. Is there a way to reverse the order?

playersFastAdapter.itemAdapter.withComparator(compareBy({ it.player.goals }, {it.player.assists}), true)


#2

Not sure about a more generic solution, but as you have integers, why not just compare by

-it.player.goals?


#3

That’s a clever solution, @mslenc. Now it’s working the way I wanted. Thanks a lot, man!


#4

Check this answer https://stackoverflow.com/a/33640865/869184, especially this way to create a comparator based on multiple properties:

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

Also you can just reverse the order of your comparator by adding .reversed() extension function call to it.