Link to home
Start Free TrialLog in
Avatar of laptopcomputer
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)getValue();
                  String sVal2 = ((value1Entity)value2)getValue();
            
            int iVal1 = 0;
            int iVal2 =0;
           
                  try { iVal1=(int)Float.parseFloat(sVal1); }
                    catch(NumberFormatException e) { }
                  try { iVal2=(int)Float.parseFloat(sVal2); }
                    catch(NumberFormatException 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;
            }
      };
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Just reverse iVal1 and iVal2 in the code
Avatar of laptopcomputer
laptopcomputer

ASKER


That does'nt seem to be working, where in the code do you replace ?

Thanks
In the if-else section
ASKER CERTIFIED SOLUTION
Avatar of spoxox
spoxox
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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);

Open in new window

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.reverseComparator(myComparator);

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.