How to sort by local strings letter sensitive?

2019-05-14 13:35发布

问题:

Suppose I have list of words like

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

I want to be sorted with polish locale like:

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

Is it possible to achieve?

UPDATE:

Suppose I have to sort list by two object parameters and also using collator. For one property I can use:

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

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

How to add to this also to sort by firstName? (so for example if there will be two same lastName then sort them by firstName)

回答1:

From here

Try something like this:

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

Update:

Make your object implement 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
}

Try this.