Reading the Java Tutorial by Oracle on interfaces which gives a example on Card
(Playing cards) I was trying to understand the default methods in interfaces. Here's the link, 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 sort
function takes a Comparator
Logic 1:
package defaultmethods;
import java.util.*;
import java.util.stream.*;
import java.lang.*;
public class SortByRankThenSuit implements Comparator<Card> {
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();
}
}
Logic 2:
myDeck.sort(
Comparator
.comparing(Card::getRank)
.thenComparing(Comparator.comparing(Card::getSuit)));
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 myDeck.sort(Comparator.comparing(Card::getRank))
which sorts by rank but after reading the documentation for thenComparing
, I am unable to understand how thenComparing
returns a Comparator
which achieves the above Logic 1. Does it internally build something like the if-else
construct as specified in Logic 1 ?