我有一组带连字符的字符串集。我想根据语言环境进行排序。
List<String> words = Arrays.asList("App - Small", "Apple", "App - Big");
Collator collator = Collator.getInstance(new Locale("en"));
// Sort Method 1
Collections.sort(words, String.CASE_INSENSITIVE_ORDER);
System.out.println(words.toString());
// Sort Method 2
collator.setStrength(Collator.PRIMARY);
Collections.sort(words, collator);
System.out.println(words.toString());
结果
String.CASE_INSENSITIVE_ORDER
[App - Big, App - Small, Apple]
Collator.PRIMARY
[App - Big, Apple, App - Small]
虽然 Collator.PRIMARY 应该进行不区分大小写的排序,但使用上述两种方法的顺序之间存在差异。如何实现与连字符一起使用的基于区域设置的不区分大小写的排序顺序。
[App - Big, App - Small, Apple] - 预期排序
最佳答案
不涉及区分大小写的问题。整理器会忽略空格和连字符,因为所有字符串都以“App”开头,所以重要的字母是“S
”、“l
”和“B
”在您的示例中,结果顺序“B
”“L
”“S
”是正确的。
关于Java 不区分大小写的本地化排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19640733/