3

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)

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
K.Os
  • 5,123
  • 8
  • 40
  • 95

1 Answers1

4

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.

Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
  • Thanks, can you see my updated question? Maybe you have idea how to combine this answer that you gave me previously – K.Os Sep 11 '18 at 20:45
  • @Konrad you should implement comparable interface in your object and do that logic in the compareTo method – Nongthonbam Tonthoi Sep 11 '18 at 21:09
  • Still not sure how exactly this can help me - i still cannot apply sorting by two properties and collator to them – K.Os Sep 11 '18 at 21:14
  • That's good solution. The only thing about it is that what when i need other Collator? Normally it is provied by Context but it will be hard to have context in some data class object that has this Comparable implemented – K.Os Sep 11 '18 at 21:30
  • @Konrad you can get context in by creating an Application class (if you haven't any) and getting the instance from there, so you can do something like `val context = MyAppClass.getInstance()` – Nongthonbam Tonthoi Sep 11 '18 at 21:36