Reputation: 327
I've got a list of Folder
objects, with getFolderName
method (returns a 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?
Upvotes: 1
Views: 249
Reputation: 521339
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. The above code is idealistic and assumes this is not a concern.
Upvotes: 1