Java排序规则忽略空间 [英] Java collation ignores space

查看:82
本文介绍了Java排序规则忽略空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我意识到Java排序规则似乎忽略了空格。

I became recently aware, that Java Collation seems to ignore spaces.

我列出了以下术语:

Amman Jost 
Ammann Heinrich 
Ammanner Josef 
Bär Walter 
Bare Werner 
Barr Burt 
Barraud Maurice

上面的顺序反映了德国所需的订购方式,即考虑了空间。
但是,使用Java排序规则

The order above reflects the desired ordering for Germany, i.e. taking space into acount. However, Java Collation using

Collator collator = Collator.getInstance(Locale.GERMANY);
Collections.sort(values, collator);

给我以下命令:

Amman Jost
Ammanner Josef
Ammann Heinrich
Bare Werner
Barraud Maurice
Barr Burt
Bär Walter

上面的结果实际上不是我所期望的,因为没有考虑空格(看起来像描述的情况此处:维基百科的字母顺序)。

The result above is actually not what I have expected, since spaces are not taken into account (looks like the case described here: Wikipedia Alphabetical order).

这是否意味着Java整理不适用于此类用例,或者我在这里做错了什么?有没有一种方法可以使Java Collat​​ion空间感知?

Does this mean, that Java Collation is not usable for such use case or am I doing something wrong here? Is there a way to make Java Collation space aware?

如果有任何意见或建议,我会很高兴。

I would be glad for any comments or recommendations.

推荐答案

您可以自定义排序规则。尝试查看源代码,以了解如何构建德语语言环境的整理器,如此答案中所述。

You can customize the collation. Try looking at the source code to see how the Collator for German locale is built, as described in this answer.

然后使其适应您的需求。 教程提供了一个起点。但是无需完成所有工作,其他人已经完成了:请参见有关捷克语完全相同的问题的博客文章。

Then adapt it to your needs. The tutorial gives a starting point. But no need to do all the work, someone else already has done it: see this blog post dealing with the exact same problem for Czech.

上面链接的解决方案的本质是:

The essence of the solution linked above is:

String rules = ((RuleBasedCollator) Collator.getInstance(Locale.GERMANY)).getRules();
RuleBasedCollator correctedCollator 
    = new RuleBasedCollator(rules.replaceAll("<'\u005f'", "<' '<'\u005f'"));

这会在下划线规则之前添加一个空格字符规则。

This adds a rule for the space character just before the rule for underscore.

我承认我还没有亲自测试过。

I confess I haven't tested this personally.

这篇关于Java排序规则忽略空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆