为什么Kotlin sortBy()似乎以相反的顺序运行?

Zor*_*gan 1 java sorting kotlin

当我表演时:

val array = arrayListOf<String?>(null, "hello", null)
array.sortBy { it == null }
println(array)
Run Code Online (Sandbox Code Playgroud)

我希望它会null首先打印值,因为这是我指定的选择器。但是,println(array)返回[hello, null, null]

为什么是这样?

for*_*pas 6

表达方式:

it == null
Run Code Online (Sandbox Code Playgroud)

返回Boolean结果truefalse,这就是您用来对数组进行排序的方式。
该值true大于false,您可以通过执行以下命令看到它:

println(false < true)
Run Code Online (Sandbox Code Playgroud)

将打印

true
Run Code Online (Sandbox Code Playgroud)

使用您的代码:

array.sortBy { it == null }
Run Code Online (Sandbox Code Playgroud)

对于表达式it == null返回的每个项目,false它都将放在它返回的任何项目之前true
与此相反:

array.sortBy { it != null }
Run Code Online (Sandbox Code Playgroud)

结果:

[null, null, hello]
Run Code Online (Sandbox Code Playgroud)