使用 Locale.TRADITIONAL_CHINESE 使用 Collator 进行错误排序
Wrong sorting with Collator using Locale.TRADITIONAL_CHINESE
我想按中文笔画数排序列表,我正在使用创建 Collator 的方法来实现它,但 TRADITIONAL_CHINESE 的 Collator 似乎有一些错误。
例如,
List<String> strList = new List<>();
strList.add("日");
strList.add("蘋");
Collections.sort(strList, new SortChinese());
class SortChinese implements Comparator<String> {
public int compare(String obj1, String obj2) {
Collator collator = Collator.getInstance(Locale.TRADITIONAL_CHINESE);
collator.setStrength(Collator.PRIMARY);
return collator.compare(obj1, obj2);
}
}
前: 日,苹果
之后:苹果,日
预期结果:日,苹果
对 android 中的中文笔画计数排序有什么想法或建议吗?
您可以删除 ShortChinese:
List<String> strList = new List<>();
strList.add("日");
strList.add("蘋");
Collator collator = Collator.getInstance(Locale.TRADITIONAL_CHINESE);
collator.setStrength(Collator.PRIMARY);
Collections.sort(strList, collator);
@propoLis 的代码对我有用(Java 8,Windows)。使用 UTF-8 编辑和编译。也许您使用的编码与编译时不同。
所以试试:
strList.add(new String(new int[] {0x65e5}, 0, 1)); // Unicode code points
strList.add(new String(new int[] {0x860b}, 0, 1));
或
strList.add("\u65e5"); // Unicode UTF-16
strList.add("\u860b");
但是你需要2次错误才能再次收到中文。
你可以试试这个:
strList.sort((o1, o2) -> compareInChinese(str1, str2));
也许您可以将其添加到您的实用程序中 class。
public static int compareInChinese(String str1, String str2) {
Collator collator = Collator.getInstance(new Locale("zh", "CN"));
collator.setDecomposition(Collator.NO_DECOMPOSITION);
collator.setStrength(Collator.PRIMARY);
return collator.compare(str1, str2);
}
我想按中文笔画数排序列表,我正在使用创建 Collator 的方法来实现它,但 TRADITIONAL_CHINESE 的 Collator 似乎有一些错误。
例如,
List<String> strList = new List<>();
strList.add("日");
strList.add("蘋");
Collections.sort(strList, new SortChinese());
class SortChinese implements Comparator<String> {
public int compare(String obj1, String obj2) {
Collator collator = Collator.getInstance(Locale.TRADITIONAL_CHINESE);
collator.setStrength(Collator.PRIMARY);
return collator.compare(obj1, obj2);
}
}
前: 日,苹果
之后:苹果,日
预期结果:日,苹果
对 android 中的中文笔画计数排序有什么想法或建议吗?
您可以删除 ShortChinese:
List<String> strList = new List<>();
strList.add("日");
strList.add("蘋");
Collator collator = Collator.getInstance(Locale.TRADITIONAL_CHINESE);
collator.setStrength(Collator.PRIMARY);
Collections.sort(strList, collator);
@propoLis 的代码对我有用(Java 8,Windows)。使用 UTF-8 编辑和编译。也许您使用的编码与编译时不同。
所以试试:
strList.add(new String(new int[] {0x65e5}, 0, 1)); // Unicode code points
strList.add(new String(new int[] {0x860b}, 0, 1));
或
strList.add("\u65e5"); // Unicode UTF-16
strList.add("\u860b");
但是你需要2次错误才能再次收到中文。
你可以试试这个:
strList.sort((o1, o2) -> compareInChinese(str1, str2));
也许您可以将其添加到您的实用程序中 class。
public static int compareInChinese(String str1, String str2) {
Collator collator = Collator.getInstance(new Locale("zh", "CN"));
collator.setDecomposition(Collator.NO_DECOMPOSITION);
collator.setStrength(Collator.PRIMARY);
return collator.compare(str1, str2);
}