[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 426
  • Last Modified:

how to sort objects ascending and descending

How would you use comparators to sort objects ascending and descending.

Suppose I want to be able to sort an object by the age field either ascending or descending.
Also I have an object that can be sorted by more than field. You can sort by name and age.
How can I implement more than 1 comparator?

0
inzaghi
Asked:
inzaghi
  • 3
  • 3
  • 2
2 Solutions
 
CEHJCommented:
You can pass the field as a parameter to the ctor of the Comparator. Reverse the comparison for asc.ssec
0
 
objectsCommented:
You would use a different Comparator for each sort order that you needed.
To get the reverse order iuse:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#reverseOrder(java.util.Comparator)
0
 
CEHJCommented:
Typo:

>>Reverse the comparison for asc.ssec

should have been

Reverse the comparison for asc/desc
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
inzaghiAuthor Commented:
I am using java 1.4
0
 
CEHJCommented:
:-)

You only need one Comparator
0
 
inzaghiAuthor Commented:
Alternatively I could have one class which implements the Comparable interface and otehr comparators I can define as annonymous classes

 public static final Comparator AGE_ORDER = new Comparator() {
             public int compare(Object o1, Object o2) {
             }
 };

 public static final Comparator NAME_ORDER = new Comparator() {
             public int compare(Object o1, Object o2) {
             }
};
0
 
objectsCommented:
> Alternatively I could have one class which implements the Comparable interface and otehr comparators I can define as annonymous classes

yes you could use inner classes for your comparators. It would still give you a seperate class for each sort order you needed, ie. one comparator per sort order.

0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now