I have a object called project
, I want to sort this project by 2 of its fields:
First: by Date(Gregorian Callander); Second: by Name(String);
I want to sort the project by date form new to old. The only way I know to do this is to reverse the collection. However I want to sort the project with same date on name(alphabetically), where reverse also reverses this part of the sort.
Is there a way to reverse only part of the sort method, or any other way to get this sorted first by a date(reverse) and then a string(normal order a-z) ?
At the moment I am overriding the object compareTo
method like so:
@Override
public int compareTo(Project project) {
int i = this.projectDate.compareTo(project.projectDate);
if(i != 0) return i;
return this.projectName.compareTo(project.projectName);
}
Date#compareTo
returns a value < 0 if this Date is before the Date argument and a value > 0 otherwise.
If you want to reverse the sort from new to old, you can just return the negative compare result:
@Override
public int compareTo(Project project) {
int i = this.projectDate.compareTo(project.projectDate);
if(i != 0) return -i; // reverse sort
return this.projectName.compareTo(project.projectName);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With