kishortry
kishortry

Reputation: 3

Multi column order using java

Hi I need any method or explanation on how we can order multiple column values in java. The output should be similar to the multiple column order output in MySQL.

for clarification please check the below link http://www.dynamicdrive.com/forums/showthread.php?19797-ORDER-BY-Multiple-Columns

Upvotes: 0

Views: 78

Answers (2)

Jason
Jason

Reputation: 11832

Let's say your object looks like this:

public DataObject {
    public String name;
    public int age;
    public String hairColour;
}

Let's say you want to sort them based on age, then hair colour, then name. You could create a comparator as follows:

public DataObjectComparator extends Comparator<DataObject> {
    public int compare(DataObject o1, DataObject o2) {
        // if the age is the same
        if(o1.age == o2.age) {
            // if the hair colour is the same
            if(o1.hairColour.compareTo(o2.hairColour) == 0) {
                // return the name comparison
                return o1.name.compareTo(o2.name);
            } else {  // else return the hair colour comparison
                return o1.hairColour.compareTo(o2.hairColour);
            }
        } else {  // else return the age comparison
            return o1 < o2 ? -1 : 1;
        }
    }
}

Upvotes: 1

Niraj Patel
Niraj Patel

Reputation: 2208

You can sort arraylist for multiple properties using below sample comparator.

public class CustomeClass implements Comparator<CustomeObject> {
    public int compare(CustomeObject o1, CustomeObject o2) {
        int value1 = o1.prop1.compareTo(o2.prop1);
        if (value1 == 0) {
            int value2 = o1.prop2.compareTo(o2.prop2);
            if (value2 == 0) {
                return o1.prop3.compareTo(o2.prop3);
            } else {
                return value2;
        }
        return value1;
    }
}

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

Upvotes: 1

Related Questions