Android Kotlin sorting by collator

Viewed 1799

I want to sort a list of objects based on one field(player.name), but in Spanish there are accents that don't have to be taken into account when ordering.

I sort the list:

strikers.sortedWith(compareBy { it.name })

But I have no idea how to apply to the above sorting

val spanishCollator = Collator.getInstance(Locale("es", "ES"))

How can I achieve this?

2 Answers

Collator class implements Comparator interface, so you can use it to compare names as following:

strikers.sortedWith(compareBy(spanishCollator) { it.name })

Here we use it as a comparator argument of compareBy function overload, that takes both the value selector { it.name } and the comparator spanishCollator that compares these values.

Something like this?

val spanishCollator = strikers.sortedWith(Comparator { s1, s2 ->
                Collator.getInstance(Locale("es", "ES")).compare(s1,s2)
            })
Related