7

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 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

11

Something like this?

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

3 Comments

I've modified it a little bit, but that is what I wanted. strikers.sortedWith(Comparator { player1, player2 -> Collator.getInstance(Locale("es", "ES")).compare(player1.name, player2.name) })
I'm glad that it helps you ^^
You're creating a new instance of Locale for every two strings compared, seems not a very efficient solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.