CompareBy 如何使用布尔表达式在 kotlin 中工作
我从官方文档中知道compareBy 使用函数序列创建一个比较器来计算比较结果。这些函数按顺序调用,接收给定值 a 和 b 并返回 Comparable 对象
。
我知道对于普通属性(例如这里的整数值)必须如何完成此操作,但是compareBy如何处理布尔条件?
在此示例中,我打算将所有 4 保留在列表顶部,然后按值的升序排序,但我不确定这个布尔表达式如何帮助我做到这一点!
fun main(args: Array<String>) {
var foo = listOf(2, 3, 4, 1, 1, 5, 23523, 4, 234, 2, 2334, 2)
foo = foo.sortedWith(compareBy({
it != 4
},{
it
}))
print(foo)
}
输出
[4, 4, 1, 1, 2, 2, 2, 3, 5, 234, 2334, 23523]
I know from official documentation that compareBycreates a comparator using the sequence of functions to calculate a result of comparison. The functions are called sequentially, receive the given values a and b and return Comparable objects
.
I know how this must be done for normal attributes like the integer value here, but how are boolean conditions handled by compareBy?
In this example, I intended to keep all 4's at the top of the list and then sort in ascending order of values, but I am not sure how this boolean expression helps me do this!
fun main(args: Array<String>) {
var foo = listOf(2, 3, 4, 1, 1, 5, 23523, 4, 234, 2, 2334, 2)
foo = foo.sortedWith(compareBy({
it != 4
},{
it
}))
print(foo)
}
Output
[4, 4, 1, 1, 2, 2, 2, 3, 5, 234, 2334, 23523]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Boolean
是Comparable
因此,当您在
compareBy
中返回it != 4
时,您正在使用布尔
的排序顺序即 false <真的。仅当it == 4
时,您的表达式才为 false,并且实际上您可以将 4 视为输出中的第一个元素。Boolean
isComparable
So when you're returning
it != 4
incompareBy
you're usingBoolean
's sort order i.e. false < true. Your expression is false only whenit == 4
, and indeed you can see the 4s as the first elements in the output.您的代码提供了两个选择器作为
vararg
到compareBy
:深入研究源代码,我们为任意两个值
a
提供了一个Comparator
code> 和b
构建:Comparator { a, b -> compareValuesByImpl(a, b, 选择器) }
最后:
最后一个代码片段演示了如果所有选择器具有相同的
diff
、a
和b
被认为是相等的,否则具有 diff != 0 的 first 选择器获胜。布尔值是可比较的。当将 4 与任何其他值(例如 2)进行比较时,您将得到:
因此,对于排序,4 比任何非 4 的值“少”
Your code provides two selectors as a
vararg
tocompareBy
:Digging into the sources we have a
Comparator
for any two valuesa
andb
built up:Comparator { a, b -> compareValuesByImpl(a, b, selectors) }
and finally:
The last code snippet demonstrates that if all selectors have the same
diff
,a
andb
are considered equal otherwise the first selector with diff != 0 wins.Booleans are comparable. When comparing 4 with any other value, say 2, you will have:
and so, for sorting, 4 is "less" then any value that is not 4