I need to sort a List of items based on a List of Filters, which are ordered by priority. However, these Filters come from the API request body, so they can change.
I have a Filter class
public class Filter {
private String fieldName;
private String order;
// Getters and Setters...
}
Some Filter Objects
Filter filter1 = new Filter("price", "desc");
Filter filter2 = new Filter("size", "asc");
My Item class goes like this:
public class Item {
private String productName;
private double size;
private double price;
// Getters and Setters...
}
Then I have to sort the Items like this:
If an Item.price equals the next Item, compare their size, and so on...
I already tried creating a Comparator for each Filter, but I'm unable to chain them, so each filter sorts the List on it's own, with no regard to the previous sorting method (sometimes flipping the whole List upside down).
I also tried implementing the Comparable interface on the Item class, but the interface method compareTo
accepts only a single parameter(the next Item), but not a List of rules.
So given a List of Items like
List<Item> items = new ArrayList<Item>(
new Item("foo", 10.0, 5.0),
new Item("bar", 6.0, 15.0),
new Item("baz", 7.0, 5.0)
);
And a List of Filters like
List<Filter> filters = new ArrayList<Filter>(
new Filter("price", "desc"),
new Filter("size", "asc")
);
I'd expect the result to be
List<Item> sortedItems = new ArrayList<Item>(
new Item("bar", 6.0, 15.0),
new Item("baz", 7.0, 5.0),
new Item("foo", 10.0, 5.0)
);
Would you please help me? Thanks in advance!
IMPORTANT: I'm not having a problem with the comparison of the fields themselves. My problem is with making a dynamic Comparator that changes its comparisons based on a List of Filters.