laptopcomputer
asked on
Java Comparator - Sorting Question
Hi All,
Below is a comparator that sorts numbers in ascending order starting with the smallest. I want to reverse this so that it sorts numbers in descending order, the largest number appearing first and so on.
Thanks for any help
public static Comparator myComparator = new Comparator(){
public int compare(Object value1, Object value2) {
String sVal1 = ((value1Entity)value1)getV alue();
String sVal2 = ((value1Entity)value2)getV alue();
int iVal1 = 0;
int iVal2 =0;
try { iVal1=(int)Float.parseFloa t(sVal1); }
catch(NumberFormatExceptio n e) { }
try { iVal2=(int)Float.parseFloa t(sVal2); }
catch(NumberFormatExceptio n e) { }
if(iVal1 == 0)
iVal1 = 9999;
if(iVal2 == 0)
iVal2 = 9999;
if(iVal1<iVal2)
return 1;
else if(iVal2<iVal1)
return -1;
else //(iVal2==iVal1)
return 0;
}
};
Below is a comparator that sorts numbers in ascending order starting with the smallest. I want to reverse this so that it sorts numbers in descending order, the largest number appearing first and so on.
Thanks for any help
public static Comparator myComparator = new Comparator(){
public int compare(Object value1, Object value2) {
String sVal1 = ((value1Entity)value1)getV
String sVal2 = ((value1Entity)value2)getV
int iVal1 = 0;
int iVal2 =0;
try { iVal1=(int)Float.parseFloa
catch(NumberFormatExceptio
try { iVal2=(int)Float.parseFloa
catch(NumberFormatExceptio
if(iVal1 == 0)
iVal1 = 9999;
if(iVal2 == 0)
iVal2 = 9999;
if(iVal1<iVal2)
return 1;
else if(iVal2<iVal1)
return -1;
else //(iVal2==iVal1)
return 0;
}
};
Just reverse iVal1 and iVal2 in the code
ASKER
That does'nt seem to be working, where in the code do you replace ?
Thanks
In the if-else section
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Once you've got the values into iValX you can just do the following in fact instead of the if-else, and give yourself a means of boolean flagging the reverseSort
return reverseSort? (iVal2 - iVal1) : (iVal1 - iVal2);
You don't need to do that. Don't complicate your comparator with reverse order, instead create a new comparator using the following
Comparator reverse = Collections.reverseCompara tor(myComp arator);
Comparator reverse = Collections.reverseCompara
All that you have to do is after running your original comparator (one that returns a list in ascending order),
do a
Collections.reverse(list);
where list is the output of the original comparator.
do a
Collections.reverse(list);
where list is the output of the original comparator.