我從官方檔案中知道 compareBy
creates 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。
我知道對于像這里的整數值這樣的普通屬性必須如何執行此操作,但是 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]
uj5u.com熱心網友回復:
Boolean是Comparable
public class Boolean private constructor() : Comparable<Boolean>
因此,當您回傳時it != 4,compareBy您使用Boolean的是排序順序,即 false < true。僅當 時您的運算式為假it == 4,實際上您可以將 4s 視為輸出中的第一個元素。
uj5u.com熱心網友回復:
您的代碼提供了兩個選擇器作為varargto compareBy:
foo.sortedWith(
compareBy(
{ it != 4 },
{ it }
)
)
深入研究我們Comparator對任何兩個值都有 aa并b建立起來的來源:Comparator { a, b -> compareValuesByImpl(a, b, selectors) }
最后:
private fun <T> compareValuesByImpl(a: T, b: T, selectors: Array<out (T) -> Comparable<*>?>): Int {
for (fn in selectors) {
val v1 = fn(a)
val v2 = fn(b)
val diff = compareValues(v1, v2)
if (diff != 0) return diff
}
return 0
}
最后一個代碼片段演示了如果所有選擇器都具有相同的diff,a并且b被認為是相等的,否則第一個具有 diff != 0 的選擇器可以決定。
布林值具有可比性。將 4 與任何其他值(例如 2)進行比較時,您將擁有:
4 != 4 false
2 != 4 true
diff = false.compareTo( true ) == -1
因此,對于排序,4 比任何非 4 的值“少”
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/440842.html
