title: How to create a comparator with dynamic rules?
body: <p>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.</p>
  
  <p>I have a Filter class</p>
  
  <pre class="lang-java prettyprint-override"><code>public class Filter {
    private String fieldName;
    private String order;
  
    // Getters and Setters...
  }
  
  </code></pre>
  
  <p>Some Filter Objects</p>
  
  <pre class="lang-java prettyprint-override"><code>Filter filter1 = new Filter("price", "desc");
  Filter filter2 = new Filter("size", "asc");
  </code></pre>
  
  <p>My Item class goes like this:</p>
  
  <pre class="lang-java prettyprint-override"><code>public class Item {
    private String productName;
    private double size;
    private double price;
  
    // Getters and Setters...
  }
  </code></pre>
  
  <p>Then I have to sort the Items like this:</p>
  
  <p>If an Item.price equals the next Item, compare their size, and so on...</p>
  
  <p>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).</p>
  
  <p>I also tried implementing the Comparable interface on the Item class, but the interface method <code>compareTo</code> accepts only a single parameter(the next Item), but not a List of rules.</p>
  
  <p>So given a List of Items like</p>
  
  <pre class="lang-java prettyprint-override"><code>List&lt;Item&gt; items = new ArrayList&lt;Item&gt;(
    new Item("foo", 10.0, 5.0),
    new Item("bar", 6.0, 15.0),
    new Item("baz", 7.0, 5.0)
  );
  </code></pre>
  
  <p>And a List of Filters like</p>
  
  <pre class="lang-java prettyprint-override"><code>List&lt;Filter&gt; filters = new ArrayList&lt;Filter&gt;(
    new Filter("price", "desc"),
    new Filter("size", "asc")
  );
  </code></pre>
  
  <p>I'd expect the result to be</p>
  
  <pre><code>List&lt;Item&gt; sortedItems = new ArrayList&lt;Item&gt;(
    new Item("bar", 6.0, 15.0),
    new Item("baz", 7.0, 5.0),
    new Item("foo", 10.0, 5.0)
  );
  </code></pre>
  
  <p>Would you please help me? Thanks in advance!</p>
  
  <p><strong>IMPORTANT:</strong> 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.</p>