我想对一些包含数字的字符串进行排序,但排序后结果变成了这样:["s1", "s10", "s11", ... ,"s2", "s21", "s22"]
。在搜索时,我发现有一个与之相同的问题(链接)。但是在我的例子中,我有一个mutableList<myModel>
,我必须将所有的字符串myModel.title
放入可变列表中,并放置在以下代码下方:
val sortData = reversedData.sortedBy {
//pattern.matcher(it.title).matches()
Collections.sort(it.title, 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)
}
})
}
我在使用.sortedBy
和Collections.sort(it.title)
时遇到了错误,请帮我修复。
Collections.sort
和sortedBy
。你可能想看一下sortWith
。此外,sortedBy
和sortedWith
是类似的(它们返回一个新的列表),而sortWith
则操作于当前列表。 - RolandObservable
/Subscriber
,这是你没有使用过的东西... - Roland