4

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)
Guilherme Lima Pereira
  • 1,402
  • 5
  • 17
  • 35
  • 1
    Useful question about sorting in Kotlin: https://stackoverflow.com/questions/33640864/how-to-sort-based-on-compare-multiple-values-in-kotlin – BakaWaii Sep 22 '17 at 16:17

3 Answers3

6
mylist.sortWith(compareBy<Player> { it.name }.thenBy { it.age }.thenBy { it.gender })

or

mylist.sortWith(compareByDescending<Player> { it.name }
    .thenByDescending { it.age }.thenBy { it.gender })
CoolMind
  • 26,736
  • 15
  • 188
  • 224
peter
  • 61
  • 1
  • 2
  • 2
    Please format your code properly. And put some explanation on the code, instead of dumping the code alone – Jayendran Aug 07 '18 at 05:16
  • I formatted the code, but not sure it works right. At least, it returns `Unit` instead of list. Better see https://stackoverflow.com/a/37259482/2914140. – CoolMind Jan 21 '19 at 16:48
2

As suggested by Mitja Slenc on Kotlin forum:

Changed to compareBy({ -it.player.goals}, {-it.player.assists})

And now it's working the way I wanted!

Guilherme Lima Pereira
  • 1,402
  • 5
  • 17
  • 35
0

you can always use compareByDescending

James Ralston
  • 1,170
  • 8
  • 11