title: Sorting Java objects using multiple keys
body: <p>I've got a collection of Duck objects and I'd like to <strong>sort them using multiple keys</strong>.</p>
  
  <pre><code>class Duck {
      DuckAge age; //implements Comparable
      DuckWeight weight; //implements Comparable
      String name;
  }
  List&lt;Duck&gt; ducks = Pond.getDucks();
  </code></pre>
  
  <p>eg. I want to sort them <strong>primarily by their weights</strong>, and <strong>secondarily by their age</strong>. If two ducks have the exact same weight and the exact same age, then let's differentiate them using their <strong>names as a tertiary key</strong>. I might do something like this:</p>
  
  <pre><code>Collections.sort(ducks, new Comparator&lt;Duck&gt;(){
      @Override
      public int compare(Duck d1, Duck d2){
          int weightCmp = d1.weight.compareTo(d2.weight);
          if (weightCmp != 0) {
              return weightCmp;
          }
          int ageCmp = d1.age.compareTo(d2.age);
          if (ageCmp != 0) {
              return ageCmp;
          }
          return d1.name.compareTo(d2.name);
      }
  });
  </code></pre>
  
  <p>Well I do this quite frequently, but this solution doesn't smell right. It doesn't scale well, and it's easy to mess up. Surely there must be a better way of sorting Ducks using multiple keys! Does anybody know of a better solution?</p>
  
  <p><strong>EDIT</strong> removed unnecessary <code>else</code> branches</p>