inzaghi
asked on
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?
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?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I am using java 1.4
then you can use reverse() to reverse list order (after sorting with your comparator)
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#reverse(java.util.List)
or you could use jakarta commons
http://jakarta.apache.org/commons/collections/api-2.1.1/org/apache/commons/collections/ComparatorUtils.html
http://jakarta.apache.org/commons/collections/api-2.1.1/org/apache/commons/collections/comparators/ComparatorChain.html
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#reverse(java.util.List)
or you could use jakarta commons
http://jakarta.apache.org/commons/collections/api-2.1.1/org/apache/commons/collections/ComparatorUtils.html
http://jakarta.apache.org/commons/collections/api-2.1.1/org/apache/commons/collections/comparators/ComparatorChain.html
:-)
You only need one Comparator
You only need one Comparator
ASKER
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) {
}
};
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) {
}
};
> 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.
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.
>>Reverse the comparison for asc.ssec
should have been
Reverse the comparison for asc/desc