用Kotlin排序

我在Kotlin中对对象进行排序时遇到问题。我上课

Home(id : String,name : String)

,我想先按名称排序,然后按ID排序,其中ID可以是:

  • 数字1,2,3,10,
  • 带有字符串的数字:1a,10-14。

此解决方案无法提供正确的结果。请不要因为id是String,所以我得到的结果是-> 1,10,3

myList = myList?.sortedWith(compareBy<Home> { it.name }.thenBy { it.id })

如何在then.by中添加正确的比较器,或者应该如何对其进行排序?

问候

@EDIT 我找到了解决方案,但是如何在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)
        }
    })
bluecapucino 回答:用Kotlin排序

$File1 = "C:\stack\A.txt"
$File2 = "C:\stack\B.txt"
$Ziel = "C:\stack\copy"

if(Test-Path -Path $File1,$File2)
{

    Move-Item -Path $File1 -Destination $Ziel
    Move-Item -Path $File2 -Destination $Ziel
}

结果:

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)
}
,

myList?.sortedWith(compareBy({ it.name },{ extractInt(it.id) }))
,

您可以使用对象声明扩展可比较的接口,并在其中放置比较两个字符串的逻辑,这样便可以在thenBy子句中使用它:

val myList= myList?.sortedWith(compareBy<Home> { it.name }.thenBy {
 object: Comparable<String>{
     override fun compareTo(other: String): Int {
         return extractInt(it.id) - extractInt(other)
     }

    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)
    }
}

})

,

它将是.thenBy { extractInt(it.id) }(您分别声明extractInt)。或仅在您需要的地方放extractInt的定义:

compareBy<Home> { it.name }.thenBy { 
    val num = it.id.replace("\\D".toRegex(),"")
    // return 0 if no digits found
    if (num.isEmpty()) 0 else Integer.parseInt(num)
}

当然,这些解决方案将考虑1010aas0相等;那真的是你想要的吗?如果没有,则可以返回一对提取的整数部分和剩余的字符串。

本文链接:https://www.f2er.com/2949921.html

大家都在问