I want to sort a list of objects of a class by 2 ways.
I am able to do custom sort by overwriting the compareTo method.
But I have two lists and I want to sort them differently.
Can I still accomplish this by calling the list.sort() method?
global class myClass implements Comparable{
public integer Total{get;set;}
public integer numOfDays{get;set;}
global Integer compareTo(Object compareTo) {
myClass compareToEmp = (myClass)compareTo;
if (Total == myClass.Total) return 0;
if (Total > myClass.Total) return 1;
return -1;
}
}
In the above example, how can I also be able to sort by "numOfDays"?
//UPDATE:
I actually wanted to sort list by single property.
But use different properties to sort different lists.
I ended up adding a new field to my class for sorting purpose.
global class myClass implements Comparable{
public integer Total{get;set;}
public integer numOfDays{get;set;}
public boolean isA {get;set;}
global Integer compareTo(Object compareTo) {
myClass compareToEmp = (myClass)compareTo;
if(isA){
if (Total == myClass.Total) return 0;
if (Total > myClass.Total) return 1;
return -1; }
else{
if (Total == myClass.numOfDays) return 0;
if (Total > myClass.numOfDays) return 1;
return -1;
}
}
}
Best Answer
If you want to apply a secondary sort, it seems that should be in your
==
logical branch. It is hard to tell based on your naming what you are going for, becausemyClass
is yourobject
type, not yourinstance
name (which is actuallycompareToEmp
).If you want to be able to sort by one key or the other depending on your needs, you will want to implement some mechanism by which you can retrieve (and toggle) the value to sort by.