我有默认的字符串比较器(在SortedSet中)有问题。问题是默认比较器无法对包含数字的好的字符串进行排序,即:在集合中,我具有:
room1, room2, room100
自然排序应该像上面一样,但是在集合中我有:
room1, room100, room2
我知道为什么会这样,但是我不知道如何更改它。
尝试使用此比较器,该比较器将删除所有非数字字符,然后将其余字符与数字进行比较:
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.2", "foo1.1", "foo", "room2.3", "room100.999", "room10", "room.3");
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 8+样式):
public static void main(String[] args) {
List<String> strings = Arrays.asList("room1.2", "foo1.1", "room2.3", "room100.999", "room10", "room.3");
Collections.sort(strings, Comparator.comparing(Application::extractDouble));
System.out.println(strings);
}
static double extractDouble(String s) {
String num = s.replaceAll("[^\\d.]", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Double.parseDouble(num);
}
结果:
[foo, room.3, foo1.1, room1.2, room2.3, room10, room100.999]
为什么我用List <String> strings = Arrays.asList(“ a”,“ aaa”)运行您的算法?结果不同于List <String>字符串= Arrays.asList(“ aaa”,“ a”); ?我相信结果应该是一样的。请告诉我是否有错误...
@Bohemian如何对行进行排序,但顺序如下:[room1,room2,room10,room100,foo]第一个-反向字母第二个-按数字顺序?
这篇文章很老,但是:@PonomarenkoOleh返回num.isEmpty()吗?1:Integer.parseInt(num); 尝试1而不是0。
不适用于Arrays.asList(“ 1000HoVBSTest”,“ 366MAC_CTX”,“ 151TBD2”);
@antnewbee我添加了适用于小数的代码版本。