https://kotlinlang.org logo
Title
w

WildRhum

07/31/2018, 11:48 AM
Hello ! If someone could help me ... I'm lost 😞 I need to sort a list of object by multiple values. It should be first sorted based on an Int and after if a boolean is true. It's working fine when I do one (Int or boolean) with sortedWith and compareBy, but don't know how to do both. Any suggestion ?
d

diesieben07

07/31/2018, 11:51 AM
list.sortedWith(compareBy({ it.firstProperty }, { it.secondProperty }))
1
n

nikolay

07/31/2018, 11:55 AM
compareBy {
        //...
      }.thenBy() {
        //...
      }
👍 1
d

diesieben07

07/31/2018, 11:57 AM
Or that.
w

WildRhum

07/31/2018, 12:04 PM
Ty, I already tried Take version, but I get a weird error .. I tried your solution Nikolay but I can't use it with this structure it seems
d

diesieben07

07/31/2018, 12:05 PM
Can you show your code and the error you get please?
w

WildRhum

07/31/2018, 12:08 PM
Ye,s it's comming
Some contexte : I try to create a bot for a card game like hearthstone which will be like a tutorial. fun getMonsterToKill(ennemyCard: Card, myCards: List<Card>): Card{ return myCards.sortedWith(compareByDescending({ it.attack - ennemyCard.defense }, { it.abilities.contains("Divine") }))[0] }
abilities is a list of string with all the abilities of the card
d

diesieben07

07/31/2018, 12:16 PM
There is no
compareByDecending
with that signature.
If you need such a comparator, you need to do
compareBy(...).reversed()
.
However in this case you do not need to sort the whole list, just do something like this:
val comparator = compareBy<Card>({ it.attack - ennemyCard.defense }, { it.abilities.contains("Divine") })
return myCards.maxWith(comparator) ?: TODO("default value if list is empty")
❤️ 1
w

WildRhum

07/31/2018, 12:19 PM
Oh .. I found code with
compareBy
, so I though
compareByDecending
would work 😞
Thanks a lot ! It seems to compile 🙂 What will be the outcome of maxWith on the boolean value ? Sorted by true ?
d

diesieben07

07/31/2018, 12:24 PM
false
will come before
true
w

WildRhum

07/31/2018, 12:25 PM
Ok, so I just need to negate :
{ it.abilities.contains("Divine") }
d

diesieben07

07/31/2018, 12:26 PM
I can only recommend to use
in
operator here
w

WildRhum

07/31/2018, 12:28 PM
Oh good idea and thank you very much, it's working just as I wanted ! I'll try to help other also, guess I won't help you much 🙃