对包含Java中的数字的字符串进行排序 [英] Sorting Strings that contains number in Java
本文介绍了对包含Java中的数字的字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对字符串的默认比较器(在SortedSet中)有问题。问题是默认比较器没有排序包含数字的好字符串,即:
在集合中我有:
I have problem with default comparator for Strings (in SortedSet). The problem is that default comparator doesn't sort good String that contains numbers i.e.: In set i have:
room1, room2, room100
自然顺序应该如上所述,但是我有以下内容:
Natural ordering should be like above but in set I have:
room1, room100, room2
我知道它为什么但我不知道如何更改它。
I know why it is but I don't know how to change it.
推荐答案
试试这个比较器,删除所有非数字字符,然后将剩余字符作为数字进行比较:
Try this comparator, which removes all non-digit characters then compares the remaining characters as numbers:
Collections.sort(strings, new Comparator<String>() {
public int compare(String o1, String o2) {
return extractInt(o1) - extractInt(o2);
}
int extractInt(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
});
这是一个测试:
public static void main(String[] args) throws IOException {
List<String> strings = Arrays.asList("room1", "foo", "room2", "room100", "room10");
Collections.sort(strings, new Comparator<String>() {
public int compare(String o1, String o2) {
return extractInt(o1) - extractInt(o2);
}
int extractInt(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
});
System.out.println(strings);
}
输出:
[foo, room1, room2, room10, room100]
这篇关于对包含Java中的数字的字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文