Solved

Java Comparator - Sorting Question

Posted on 2008-06-17
7
1,086 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
ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

 
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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
simple java question 3 56
eclipse buid path vs tomcat lib path 10 24
CSV file parsing thru Java 13 31
Java: The Public Class Main 4 17
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…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.

809 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