要对其进行排序,您必须使用Comparator。比较器合约在方法 compare here
中进行了描述
比较它的两个参数的顺序。如果参数相等,则返回零,如果第一个参数小于第二个,则返回负数,如果第一个参数大于第二个,则返回正数。
因此,在我们的例子中,我们使用两个字符串 a 和 b,然后查看 k 的位置。
示例:
a = "clock" // position of 'k' is 4
b = "kite" // position of 'k' is 0
比较这两个 4 - 0 = 4 得到一个正数,这意味着第一个参数大于第二个。
a = "kite" // position of 'k' is 0
b = "rekt" // position of 'k' is 3
比较这两个0 - 3 = -3 得到一个负数,这意味着第一个参数小于第二个。
代码:
var list = mutableListOf("clock", "kite", "rekt", "abcd")
list.retainAll { it.contains("k") }
// Ascending Order
list.sortWith(Comparator {a, b -> a.indexOf('k') - b.indexOf('k')})
println(list) // [kite, rekt, clock]
// Descending Order
list.sortWith(Comparator {a, b -> b.indexOf('k') - a.indexOf('k')})
println(list) // [clock, rekt, kite]
// Cleaner and more concise syntax thanks to @Tenfour04
list.sortWith( compareBy { it.indexOf('k') } )
list.sortWith( compareByDescending { it.indexOf('k') } )