如何按本地字符串字母排序敏感?

问题描述 投票:3回答:1

假设我有像这样的单词列表

a, b, c, ą, ć, z, ż

我希望使用波兰语语言环境进行排序,例如:

a, ą, b, c, ć, z, ż

有可能实现吗?

更新:

假设我必须按两个对象参数排序列表,并使用collat​​or。对于我可以使用的一个属性:

val collator = Collator.getInstance(context.getResources().getConfiguration().locale)

myList.sortedWith(compareBy(collator,  { it.lastName.toLowerCase() }))

如何添加到这个也按firstName排序? (例如,如果有两个相同的lastName然后按firstName排序)

kotlin functional-programming
1个回答
3
投票

来自here

尝试这样的事情:

val list = arrayListOf("a", "b", "c", "ą", "ć", "z", "ż")
val coll = Collator.getInstance(Locale("pl","PL"))
coll.strength = Collator.PRIMARY
Collections.sort(list, coll)
println(list)

更新:

使您的对象实现Comparable:

override fun compareTo(other: YourObject): Int {
    val coll = Collator.getInstance(Locale("pl","PL"))
    coll.strength = Collator.PRIMARY
    val lastNameCompareValue =  coll.compare(lastName?.toLowerCase(Locale("pl","PL")),other.lastName?.toLowerCase(Locale("pl","PL")))
    if (lastNameCompareValue != 0) {
        return lastNameCompareValue
    }
    val firstNameCompareValue =  coll.compare(firstName?.toLowerCase(Locale("pl","PL")),other.firstName?.toLowerCase(Locale("pl","PL")))
    return firstNameCompareValue
}

试试这个。

© www.soinside.com 2019 - 2024. All rights reserved.