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?
In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.
Using sort(), lamba, index(): The sort() function does the required in-place sorting(without creating a separate list to store the sorted order) along with a lambda function with a key to specify the function execution for each pair of tuples, the index() function helps to get the order from our custom list list_2.
Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
The sort () method is used to sort the objects of a list.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With