How to custom order/sort objects in a list

Viewed 1039

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?

3 Answers
Related