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.
And minByOrNull giving the max value, seems like a bug
Here is a link to kotlin playground if someone wants to try it, https://pl.kotl.in/tVlAOBWq4
CodePudding user response:
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()
CodePudding user response:
Adding to accepted answer, you don't need to convert to int at last.
"8,10".split(",").map { it.toInt() }.maxByOrNull { it }
As the map would transform the char
to nt
and maxByOrNull
would return value as Int?