[英]Comparator to be used with Collections.sort() for a alphanumberic list
So I have a list of a bunch of alphanumeric items like... 所以我有一堆字母数字项目列表,如...
"123456"
"alpha"
"tango"
"beta"
...
I was looking to use Collections.sort()
for the sorting of this list, but I need to sort in the order (1234,AAAA,aaaa,BBBB,bbbb,...)
with numbers first, followed by upper then lower case words. 我希望使用Collections.sort()
来排序这个列表,但是我需要(1234,AAAA,aaaa,BBBB,bbbb,...)
顺序排序(1234,AAAA,aaaa,BBBB,bbbb,...)
,然后是大小写然后小写话。 All the elements are strings including any apparent numbers. 所有元素都是字符串,包括任何明显的数字。 Would Collections.sort()
handle this case since they are all actually strings, or if not what Comparator
would I use to accomplish this? Collections.sort()
处理这种情况,因为它们实际上都是字符串,或者如果不是我将使用什么Comparator
来实现这一点? Or is there some other way that might be more efficient to accomplish this like using regular expressions? 或者是否有其他方法可以更有效地完成此操作,如使用正则表达式?
Thanks. 谢谢。
You could use a Collator : 你可以使用Collator :
List<String> list = Arrays.asList("1234","AAAA","aaaa","BBBB","bbbb");
Collator c = Collator.getInstance(Locale.ENGLISH);
c.setStrength(Collator.CANONICAL_DECOMPOSITION);
Collections.sort(list);
System.out.println("without collator: " + list);
Collections.sort(list, c);
System.out.println("with collator: " + list);
outputs: 输出:
without collator: [1234, AAAA, BBBB, aaaa, bbbb] 没有整理者:[1234,AAAA,BBBB,aaaa,bbbb]
with collator: [1234, AAAA, aaaa, BBBB, bbbb] 与collator:[1234,AAAA,aaaa,BBBB,bbbb]
Note: you may need a different collator for what you need although this one seems fine. 注意:您可能需要一个不同的整理器来满足您的需求,尽管这个看起来很好。 In the worst case scenario, you can create a RuleBaseCollator
with your specific rules . 在最坏的情况下,您可以使用特定规则创建RuleBaseCollator
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.