Solved

Java Comparator - Sorting Question

Posted on 2008-06-17
7
1,079 Views
Last Modified: 2013-12-29
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;
            }
      };
0
Comment
Question by:laptopcomputer
7 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 21804891
Just reverse iVal1 and iVal2 in the code
0
 

Author Comment

by:laptopcomputer
ID: 21805616

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

Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 21805685
In the if-else section
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 11

Accepted Solution

by:
spoxox earned 250 total points
ID: 21805727
This compare method describes how to look at two objects and decide which is greater than the other. Some sort method (not shown) will rely on this compare method in order to sort several of these objects (two at a time).

When writing a compare method, you decide what you want to measure in order to decide the "greater than/less than" relationship. If your objects are cars, you might decide to use speed (car1.maxSpeed > car2.maxSpeed). If your objects are shirts, you might decided to use sizes (if(shirt1.size == "XXL" && shirt2.size == "XL") return 1).

In this case, you're taking an int representation...
...of a String representation....
...of the object, and comparing that.

You decided if iVal1 < iVal2 return 1.

To sort descending, rather than ascending, you can change your sort or your compare. You've chosen to change the compare.

So your compare method (comparator) must answer opposite to before - it's telling which (of two) is larger, not which is smaller.

So reversing
if (iVal1 < iVal2) return 1

will yield either
if(iVal2 < iVal1) return 1 // per CEHJ

or
if(iVal1 > iVal2) return 1


Make sense?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 21805776
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

0
 
LVL 92

Expert Comment

by:objects
ID: 21808164
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);

0
 

Expert Comment

by:gunacesun
ID: 21816396
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.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 67
servlet requestdispatcher include and forward differences 1 24
ForLoop Example 3 40
how to add new optional parameter to JSP 1 29
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now