How to implement Three Level Sort ?
I am performing a complex search and get a List of Object. Now, the problem is I have to sort this list in three levels. That is,
If I have Object like this
public class A {
private String id ; // unique for every record
private String attr1;
private String attr2;
private String attr3;
private String attr4;
}
then I have to Sort the List of above type of objects
First level -attr1 as Asc
Second level -attr2 as Asc
third level - attr3 as desc
Could u suggest some way to implement this.
If you are going to sort objects then those objects are going to implement Comparable, aren't they? So your compareTo() method should look like this:public int compareTo(Object o) {
A other = (A)o;
int result = this.attr1.compareTo(other.attr1);
if (result == 0) {
result = this.attr2.compareTo(other.attr2);
if (result == 0) {
result = - this.attr3.compareTo(other.attr3);
}
}
return result;
}
I would suggest using the built in Collections framework for sorting.
have class A implement the Comparable interface then implement the compareTo method as follows:
public int compareTo(Object o) {
A a = (A)o; // <-- may cause ClassCastException if (o instanceof A) != true, but that should not be a problem.
int value = attr1.compareTo(a.attr1);
if (value != 0) return value;
value = attr2.compareTo(a.attr2);
if (value != 0) return value;
value = a.attr3.compareTo(attr3); //Notice I switched a.attr3 and attr3 for desc
return value;
}
That should do it for you.
Now put everything into an instance of java.util.List and pass that to java.util.Collections.sort(java.util.List);
If you didn't create class A, and therefore can't add a method to it, then implement a Comparator. The idea is the same, just look at the java.util.Comparator API and use java.util.Collection.sort(java.util.List, java.util.Comparator) method to sort;