Hello ! If someone could help me ... I'm lost :dis...
# announcements
w
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
Copy code
list.sortedWith(compareBy({ it.firstProperty }, { it.secondProperty }))
1
n
Copy code
compareBy {
        //...
      }.thenBy() {
        //...
      }
👍 1
d
Or that.
w
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
Can you show your code and the error you get please?
w
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
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:
Copy code
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
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
false
will come before
true
w
Ok, so I just need to negate :
{ it.abilities.contains("Divine") }
d
I can only recommend to use
in
operator here
w
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 🙃