[英]Ordering an array with special characters like accents
Does somebody knows how to order an array with words with special characters like accents?有人知道如何使用带有特殊字符(如重音)的单词对数组进行排序吗?
Arrays.sort(anArray);
returns 'Albacete'
before 'Álava'
, and I want 'Álava'
before 'Albacete'
.回报
'Albacete'
前'Álava'
,我想'Álava'
前'Albacete'
。
Thanks a lot非常感谢
If you just want to sort the strings as if they didn't have the accents, you could use the following:如果您只想对字符串进行排序,就好像它们没有重音一样,您可以使用以下命令:
Collections.sort(strs, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
o1 = Normalizer.normalize(o1, Normalizer.Form.NFD);
o2 = Normalizer.normalize(o2, Normalizer.Form.NFD);
return o1.compareTo(o2);
}
});
Related question:相关问题:
For more sophisticated use cases you will want to read up on java.text.Collator
.对于更复杂的用例,您需要阅读
java.text.Collator
。 Here's an example:下面是一个例子:
Collections.sort(strs, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Collator usCollator = Collator.getInstance(Locale.US);
return usCollator.compare(o1, o2);
}
});
If none of the predefined collation rules meet your needs, you can try using the java.text.RuleBasedCollator
.如果没有预定义的整理规则满足您的需求,您可以尝试使用
java.text.RuleBasedCollator
。
You should take a look at RuleBasedCollator你应该看看RuleBasedCollator
RuleBasedCollator class is a concrete subclass of Collator that provides a simple, data-driven, table collator.
RuleBasedCollator 类是 Collator 的具体子类,它提供了一个简单的、数据驱动的表格整理器。 With this class you can create a customized table-based Collator.
使用这个类,您可以创建一个自定义的基于表格的 Collator。 RuleBasedCollator maps characters to sort keys.
RuleBasedCollator 将字符映射到排序键。
RuleBasedCollator has the following restrictions for efficiency (other subclasses may be used for more complex languages) : RuleBasedCollator 对效率有以下限制(其他子类可能用于更复杂的语言):
If a special collation rule controlled by a is specified it applies to the whole collator object.
如果指定了由 a 控制的特殊整理规则,则它适用于整个整理器对象。 All non-mentioned characters are at the end of the collation order.
所有未提及的字符都位于整理顺序的末尾。
use a comparator like the below :) and sort your list使用如下所示的比较器 :) 并对您的列表进行排序
Comparator<String> accentIgnorantComparator = (o1, o2) -> {
return StringUtils.stripAccents(o1).compareTo(StringUtils.stripAccents(o2));
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.