When I perform:
val array = arrayListOf<String?>(null, "hello", null)
array.sortBy { it == null }
println(array)
I expect it would print null values first as that's the selector I specified. However, println(array) returns [hello, null, null].
Why is this?
The expression:
it == null
returns a Boolean result true or false and this is what you use to sort the array.
The value true is greater than false, you can see it by executing:
println(false < true)
which will print
true
With your code:
array.sortBy { it == null }
for every item that the expression it == null returns false it will be placed before any item for which it will return true.
So do the opposite:
array.sortBy { it != null }
Result:
[null, null, hello]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With