按字母顺序对列表进行排序,同时忽略大小写?

nto*_*tio 4 kotlin

我有一个艺术家姓名列表,我想按字母顺序排序,例如,如下列表:

val artists = listOf("Artist", "an Artist", "Cool Artist")

会成为:

[“艺术家”、“艺术家”、“酷艺术家”]

为了对它们进行排序,我使用:

artists.sortBy { it }

问题是 kotlin 似乎将大写 A 和小写 a 视为单独的字符 [可能是因为它们的 ASCII 顺序],导致排序顺序如下:

[Artist, Cool Artist, an Artist]

我可以写这样的东西:

artists.sortBy { it.toUpperCase() }

让所有字符都受到相同的对待,但这很可能会在其他语言中引起问题。

有没有办法让 kotlin 按字母顺序排序,同时忽略字符是小写还是大写?

nto*_*tio 11

我找到了一种更好的方法来按不区分大小写的顺序进行排序。list.sortWith {}您可以与compareBy()使用 的调用一起使用String.CASE_INSENSITIVE_ORDER。像这样:

artists.sortWith(
    compareBy(String.CASE_INSENSITIVE_ORDER, { it.name })
)
Run Code Online (Sandbox Code Playgroud)

如果你只有一堆字符串,你可以这样做:

artists.sortWith(
    compareBy(String.CASE_INSENSITIVE_ORDER, { it })
)
Run Code Online (Sandbox Code Playgroud)

这似乎排序正确,不像list.sortBy {}.