Android Kotlin按collat​​or排序

nie*_*gus 2 sorting android kotlin

我想基于一个字段(player.name)对对象列表进行排序,但在西班牙语中存在重音,在订购时不必考虑这些重音.

我对列表进行排序:

strikers.sortedWith(compareBy { it.name })
Run Code Online (Sandbox Code Playgroud)

但我不知道如何申请上述排序

val spanishCollator = Collator.getInstance(Locale("es", "ES"))
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

问候,迭戈

Ily*_*lya 9

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

strikers.sortedWith(compareBy(spanishCollator) { it.name })
Run Code Online (Sandbox Code Playgroud)

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.


nhp*_*nhp 6

像这样的东西?

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

  • 您正在为每两个比较的字符串创建一个新的 Locale 实例,这似乎不是一个非常有效的解决方案。 (2认同)