Solved

Java Comparator - Sorting Question

Posted on 2008-06-17
7
1,069 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

757 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

20 Experts available now in Live!

Get 1:1 Help Now