Java比较器字母数字字符串 [英] Java Comparator alphanumeric strings
本文介绍了Java比较器字母数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现我的自定义比较器,以这种特殊方式对键映射进行排序:
I want to implement my custom Comparator to sort a map of keys in this particular way:
1
2
3
4
4a
4b
5
6
11
12
12a
...
我不知道该怎么做.我仅对数值实施了此操作:
And I dont know how can do it exactly. I have impelemented this only for numeric values:
aaa = new TreeMap<String, ArrayList<ETrack>>(
new Comparator<String>()
{
@Override
public int compare(String s1, String s2)
{
return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
}
});
但这并不是完整的解决方案.有什么主意吗?
But this is not obiouslly the complete solution. Any idea?
推荐答案
一种方法是将字符串映射到对象,并让这些对象实现 Comparable
.
One approach is to map the strings to objects and let those objects implement Comparable
.
您可以简化操作.如果您喜欢正则表达式,即使效率不高,也可以使用此技巧:
You can do it simpler. If you like regular expressions, you can use this trick, even though it is not too efficient:
// Make sure not to compile the pattern within the method, to spare us some time.
Pattern p = Pattern.compile("^([0-9]+)([a-z]?)$");
/**
* Converts a string to a sortable integer, ensuring proper ordering:
* "1" becomes 256
* "1a" becomes 353
* "1b" becomes 354
* "2" becomes 512
* "100" becomes 25600
* "100a" becomes 25697
*/
int getSortOrder(String s) {
Matcher m = p.matcher(s);
if(!m.matches()) return 0;
int major = Integer.parseInt(m.group(1));
int minor = m.group(2).isEmpty() ? 0 : m.group(2).charAt(0);
return (major << 8) | minor;
}
像这样使用它:
new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return getSortOrder(s1) - getSortOrder(s2);
}
}
这篇关于Java比较器字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文