[英]Sort list of custom objects in Java using alphanumeric values
I've got a list of Folder
objects, with getFolderName
method (returns a String
).我有一个带有
getFolderName
方法的Folder
对象列表(返回一个String
)。
I'm trying to sort the list but I'm having an issue where the order is incorrect because some of the folder names starts with numeric values like:我正在尝试对列表进行排序,但我遇到了顺序不正确的问题,因为某些文件夹名称以数值开头,例如:
Here is my code:这是我的代码:
Collections.sort(folders, new Comparator<Folder>() {
@Override
public int compare(Folder folder1, Folder folder2) {
return Integer.compare(folder1.getFolderName(), folder2.getFolderName());
}
});
Current output:电流输出:
Expected output:预期输出:
What am I missing to sort the list correctly?我缺少什么来正确排序列表?
I think the logic you want here is to first compare the folder names alphabetically, and then in the case of two folders having the same name, break the tie using the leading number.我认为您在这里想要的逻辑是首先按字母顺序比较文件夹名称,然后在两个文件夹具有相同名称的情况下,使用前导数字打破平局。 We can try something along these lines:
我们可以尝试以下方式:
Collections.sort(folders, new Comparator<Folder>() {
@Override
public int compare(Folder folder1, Folder folder2) {
String f1 = folder1.getFolderName();
String f2 = folder2.getFolderName();
String f1name = f1.replaceAll("\\d+\\s+(.*)", "$1");
String f2name = f2.replaceAll("\\d+\\s+(.*)", "$1");
if (f1name.compareTo(f2name) != 0) {
return f1name.compareTo(f2name);
}
else {
int num1 = Integer.parseInt(f1.replaceAll("(\\d+)\\b.*", "$1"));
int num2 = Integer.parseInt(f2.replaceAll("(\\d+)\\b.*", "$1"));
return Integer.compare(num1, num2);
}
}
});
Note that I omitted things like null
checks in multiple places and other sanity checks.请注意,我省略了多个地方的
null
检查和其他健全性检查等内容。 The above code is idealistic and assumes this is not a concern.上面的代码是理想化的,并假设这不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.