How to custom order/sort objects in a list

Krishna Chaitanya :

I have a list of objects which I want to order/sort in a specific order.

I have a list of Promotion objects. Each promotion will have a description. Two out of all the promotions will have description set to "premium" and "ordinary"

I want to order/sort the list such that promotion with description "premium" should always be at the end of the list and promotion with description "ordinary" show always be at list.size - 1 position. Example below

[{description=...}, {description=...}, ..... {description=ordinary}, {description=premium}]

I tried using Collections.sort to sort the objects by passing a custom Comparator like below

public int compare(Promotion p1, Promotion p2) {
        if(p1.getDescription().equals("ordinary")) {
    return -size-1; // size is the size of the list passed as a constructor argument to the Comparator.
    }
if(p1.getDescription().equals("premium")) {
    return -size;
}
return 0;
}

I tried with the above code and I did not get the desired output while testing.

I later added another check in each of the if conditions to check to check description in p2 objects as well like below

p1.getDescription().equals("premium") || p2.getDescription().equals("premium")

What am I doing wrong here? Or am I using Collections.sort in wrong way? Can anyone please suggest/help me?

Alnour Alharin :

The Comparator method compare takes two elements and returns a negative value if x < y, 0 if x equals y or a positive value if x > y.

In this case you can put the classes in an array sorted with priorities like this:

String classes[] = new String[]{"premimum", "ordinary", "less than ordinary"};

then you can compare with indices of the elements like this:

public int compare(Promotion p1, Promotion p2) {
Integer index1 = getIndexInsideClasses(p1.getDescription);
Integer index2 = getIndexInsideClasses(p2.getDescription);
       return index1.compareTo(index2);
   }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=468881&siteId=1