我在 Kotlin 中对对象进行排序时遇到问题。我有课
Home(id : String, name : String)
我想先按名称排序,然后按 ID 排序,其中 ID 可以是:
- 数字,例如 1、2、3、10,
- 带字符串的数字:1a,10-14。
此解决方案未提供正确的结果。请注意,id 是字符串,所以我得到的结果是 -> 1, 10, 2, 3
myList = myList?.sortedWith(compareBy<Home> { it.name }.thenBy { it.id })
如何添加then.by
正确的比较器,或者应该如何排序?
问候
@编辑
我找到了解决方案,但如何在 thenBy
中添加它?
Collections.sort(strings, object : Comparator<String> {
override fun compare(o1: String, o2: String): Int {
return extractInt(o1) - extractInt(o2)
}
fun extractInt(s: String): Int {
val num = s.replace("\\D".toRegex(), "")
// return 0 if no digits found
return if (num.isEmpty()) 0 else Integer.parseInt(num)
}
})
最佳答案
data class Person(
val name: String,
var id: String
)
fun sortPersonsWithParsedIds() {
val p1 = Person("abc", "2")
val p2 = Person("abc", "1")
val p3 = Person("xyz", "10kafsd")
val p4 = Person("xyz", "1asda")
val p5 = Person("pqr", "2aaa")
val p6 = Person("pqr", "20")
val p7 = Person("pqr", "20aa")
val list = listOf(p1, p2, p3, p4, p5, p6, p7)
val sortedList = list.sortedWith(compareBy({ it.name }, { v -> extractInt(v.id) }))
sortedList.forEach { println(it) }
}
private fun extractInt(s: String): Int {
val num = s.replace("\\D".toRegex(), "")
// return 0 if no digits found
return if (num.isEmpty()) 0 else Integer.parseInt(num)
}
结果:
Person(name=abc, id=1)
Person(name=abc, id=2)
Person(name=pqr, id=2aaa)
Person(name=pqr, id=20)
Person(name=pqr, id=20aa)
Person(name=xyz, id=1asda)
Person(name=xyz, id=10kafsd)
关于在 Kotlin 中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59265887/