Search code examples
javakotlincollator

Passing locale to sort strings alphabetically


I have a list of strings that I would like to sort alphabetically, depending on the user's locale. To do this I use Collator:

val collator = Collator.getInstance()
return collator.compare(stringOne, stringTwo)

By default, Locale.getDefault() is passed to the collator, but I would like to use sorting by locale, which we will receive from the user, with the transfer of language and country. For example:

val col2 = Collator.getInstance(Locale("en", "US"))

or

val col2 = Collator.getInstance(Locale("en", "EN"))

Solution

  • As far as I understand your problem, you just need a way to pass the locale to your Collator.You'll need a Locale instance to get the job done. Something like:

    import java.text.Collator
    import java.util.*
    
    fun main() {
        val list = ArrayList<String>()
        list.add("árbol")
        list.add("único")
        list.add("cosas")
        list.add("fútbol")
    
        val spanishLocale = Locale("es", "ES")
        val collator = Collator.getInstance(spanishLocale)
    
        // Sort the list using the Collator instance
        Collections.sort(list, collator)
    
        println(list)
    }
    
    

    CODE DEMO

    You can read more around this in this blog post.