title: Chain of comparators in java
body: <p>Reading the <a href="https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html" rel="noreferrer">Java Tutorial by Oracle on interfaces</a> which gives a example on <code>Card</code> (Playing cards) I was trying to understand the <a href="https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html" rel="noreferrer">default methods in interfaces</a>. Here's the <a href="https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html" rel="noreferrer">link</a>, section "Integrating default methods in existing interfaces". Now in the last section they sorted the Cards first by rank and then by suits. Following logics have been given. Assume that whatever interfaces, functions or classes that are used have been defined and <code>sort</code> function takes a <code>Comparator</code></p>
  
  <p>Logic 1:</p>
  
  <pre><code>package defaultmethods;
  
  import java.util.*;
  import java.util.stream.*;
  import java.lang.*;
  
  public class SortByRankThenSuit implements Comparator&lt;Card&gt; {
      public int compare(Card firstCard, Card secondCard) {
          int compVal =
              firstCard.getRank().value() - secondCard.getRank().value();
          if (compVal != 0)
              return compVal;
          else
              return firstCard.getSuit().value() - secondCard.getSuit().value(); 
      }
  }
  </code></pre>
  
  <p>Logic 2:</p>
  
  <pre><code>myDeck.sort(
      Comparator
          .comparing(Card::getRank)
          .thenComparing(Comparator.comparing(Card::getSuit)));
  </code></pre>
  
  <p>Now I am having some problems in understanding the second logic. I read the comparator interfaces and the new static methods which have been included in Java 1.8 . Now I understand something like this <code>myDeck.sort(Comparator.comparing(Card::getRank))</code> which sorts by rank but after reading <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#thenComparing-java.util.Comparator-" rel="noreferrer">the documentation for <code>thenComparing</code></a> , I am unable to understand how <code>thenComparing</code> returns a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a> which achieves the above Logic 1. Does it internally build something like the <code>if-else</code> construct as specified in Logic 1 ? </p>