Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing part of the CompareTo method from custom objects

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);

}
like image 669
D.Blazer Avatar asked Feb 06 '23 16:02

D.Blazer


1 Answers

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);
}
like image 139
Modus Tollens Avatar answered Feb 09 '23 06:02

Modus Tollens