- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试使用 Locale.SIMPLIFIED_CHINESE 对中文国家/地区列表进行排序,这似乎是使用拼音(拼音字母表,即字符根据其拉丁对应组合从 A 到 Z 排序)进行排序。
但我发现有些情况下订单不好。例如:
正确的顺序应该是梵 < 中,但是顺序是相反的。
String[] characters = new String[] {"梵", "中"};
List<String> list = Arrays.asList(characters);
System.out.println("Before sorting...");
System.out.println(list.toString());
Collator collator = Collator.getInstance(Locale.SIMPLIFIED_CHINESE);
collator.setStrength(Collator.PRIMARY);
Collections.sort(list, collator);
System.out.println("After sorting...");
System.out.println(list.toString());
这段代码的结果是:
Before sorting...
[梵, 中]
After sorting...
[中, 梵]
再深入一点,我发现了 Java 应用 Locale.SIMPLIFIED_CHINESE 的规则。您可以在下一张图片中找到: https://postimg.cc/image/4t915a7gp/full/ (注意梵在中之后)
我意识到在我用红色突出显示的<口<口<口<口<口之前,所有字符都是根据它们的拉丁文对应组合从A到Z排序的。但是,在<口<口<口<之后口<口符号,字符按照字符的组成顺序排列。例如,如果所有字符都有相同的部分(通常是字符的左侧部分),则将它们分组在一起,而不是根据 A 到 Z 规则。
另外,<口<口<口<口<口之后的字符都是不太常见的汉字。因此,梵不像中那样常见,所以它放在<口<口<口<口<口之后。
我想知道为什么这个决定,如果是故意的。但它会导致错误的排序。我不知道如何为此找到解决方案。
最佳答案
Java 中整理器提供的排序顺序基于书写该字符所需的笔画。
请参阅下面的小片段进行演示。笔划编号取自 Wikitionary
// the unicode character and the number of strokes
String[] characters = new String[]{
"\u68B5 (11)", "\u4E2D (4)",
"\u5207 (4)", "\u5973 (3)", "\u898B (7)"
};
List<String> list = Arrays.asList(characters);
System.out.println("Before sorting...");
System.out.println(list.toString());
Collator collator = Collator.getInstance(Locale.TRADITIONAL_CHINESE);
collator.setStrength(Collator.PRIMARY);
System.out.println();
Collections.sort(list, collator);
System.out.println("After sorting...");
System.out.println(list.toString());
输出
Before sorting...
[梵 (11), 中 (4), 切 (4), 女 (3), 見 (7)]
After sorting...
[女 (3), 中 (4), 切 (4), 見 (7), 梵 (11)]
有增强请求JDK-6415666根据 Unicode 整理顺序实现排序顺序。但是按照有关Java 8 supported locale的信息它没有在 Java 8 中实现。
编辑 使用来自 icu4j 的整理器的排序顺序是
[梵 (11), 見 (7), 女 (3), 切 (4), 中 (4)]
ICU4J 代码片段
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.RuleBasedCollator
...
Locale locale = new Locale("zh", "", "PINYIN");
Collator collator = (RuleBasedCollator) Collator.getInstance(locale);
关于java - 使用 Locale.SIMPLIFIED_CHINESE 的 Collator 排序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33672422/
我正在尝试使用 Locale.SIMPLIFIED_CHINESE 对中文国家/地区列表进行排序,这似乎是使用拼音(拼音字母表,即字符根据其拉丁对应组合从 A 到 Z 排序)进行排序。 但我发现有些情
我是一名优秀的程序员,十分优秀!