Search code examples
androidkotlinmax

maxByOrNull not returning the max value?


I was just trying out 2 scenarios using maxByOrNull

"6,9".split(",").maxByOrNull { it }?.toInt()

and

"8,10".split(",").maxByOrNull { it }?.toInt()

The first statement returns 9, which is correct but the 2nd one returns 8. I tried 10 and 11 then it's working. Seems like if we are comparing a single digit and another single digit it's working but not working if the number of digits are different. enter image description here

And minByOrNull giving the max value, seems like a bug

enter image description here

Here is a link to kotlin playground if someone wants to try it, https://pl.kotl.in/tVlAOBWq4


Solution

  • You're comparing strings - the string "9" and the string "10", which compares string character by character. If you want to compare them as integers, you should map each string to its integer value:

    "8,10".split(",").map { it.toInt() }.maxByOrNull { it }?.toInt()