字符串的更改排序顺序包括特殊字符(例如"_") [英] Change sort order of strings includes with a special character (e.g. "_")
问题描述
PHP脚本以降序输出电子邮件地址列表,如下所示:
A PHP script outputs a list of e-mail addresses in descending order like following:
_abc_@testmail.com
_abc45_@testmail.com
_abc2_@testmail.com
ypaux2aux@yahoo.com
yaremchuk56@testmail.com
vasillevn@hotmail.com
ugur@hotmail.com
twes@gmail.com
tukaux@yahoo.com
ttsetaux1@yahoo.com
tra@testmail.com
在Java中,我从这些电子邮件中创建一个ArrayList,然后以降序排序.结果是不同的:
In Java, I'm creating an ArrayList from these e-mails, then sorting in descending order. The result is different:
ypaux2aux@yahoo.com
yaremchuk56@testmail.com
vasillevn@hotmail.com
ugur@hotmail.com
twes@gmail.com
tukaux@yahoo.com
ttsetaux1@yahoo.com
tra@testmail.com
_abc45_@testmail.com
_abc2_@testmail.com
_abc_@testmail.com
差异是由下划线"_"引起的.我想实现与PHP脚本相同的排序顺序.我怎样才能做到这一点?我无法访问PHP代码.
The difference is caused by the underscore "_". I want to achieve the same sort order as the PHP script. How can I do this? I've no access to the PHP code.
我使用的Java测试代码是:
The Java test code I used is:
import java.util.ArrayList;
import java.util.Collections;
public class sorty {
public static void main(String[] args) {
ArrayList<String> listStrings = new ArrayList<>();
listStrings.add("_abc_@testmail.com");
listStrings.add("_abc45_@testmail.com");
listStrings.add("_abc2_@testmail.com");
listStrings.add("ypaux2aux@yahoo.com");
listStrings.add("yaremchuk56@testmail.com");
listStrings.add("vasillevn@hotmail.com");
listStrings.add("ugur@hotmail.com");
listStrings.add("twes@gmail.com");
listStrings.add("tukaux@yahoo.com");
listStrings.add("ttsetaux1@yahoo.com");
listStrings.add("tra@testmail.com");
for (int i = 0; i < listStrings.size(); i++) {
System.out.println(listStrings.get(i));
}
Collections.sort(listStrings);
Collections.reverse(listStrings);
for (int i = 0; i < listStrings.size(); i++) {
System.out.println(listStrings.get(i));
}
;
}
}
推荐答案
我会使用适当的 Collator
.实现自己的比较器不是最琐碎的事情.最好的是,如果您对默认值之一满意.例如
I would use an appropriate Collator
. Implementing your own comparator isn't the
most trivial thing. The nicest would be if you where happy with one of the defaults. e.g.
Collections.sort(listStrings, Collator.getInstance(Locale.US));
或类似.
If none of the existing ones works for you then using a rule based collator would make your intent clearer then implementing a comparator imo:
String rules = "< a < b < c < '_'" //etc
Collections.sort(listStrings, new RuleBasedCollator(rules));
这篇关于字符串的更改排序顺序包括特殊字符(例如"_")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!