Chain of comparators in java -


reading java tutorial oracle on interfaces gives example on card (playing cards) trying understand default methods in interfaces. here's link, section "integrating default methods in existing interfaces". in last section sorted cards first rank , suits. following logics have been given. assume whatever interfaces, functions or classes used have been defined , sort function takes 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 having problems in understanding second logic. read comparator interfaces , new static methods have been included in java 1.8 . understand mydeck.sort(comparator.comparing(card::getrank)) sorts rank after reading the documentation thencomparing , unable understand how thencomparing returns comparator achieves above logic 1. internally build if-else construct specified in logic 1 ?

yes, creates internally similar, more intermediate lambdas. assuming getrank , getsuit methods return instances of comparable classes rank , suit, in case have:

function<card, rank> torank = card::getrank; comparator<card> comp1 = (a, b) -> torank.apply(a).compareto(torank.apply(b)); function<card, suit> tosuit = card::getsuit; comparator<card> comp2 = (a, b) -> tosuit.apply(a).compareto(tosuit.apply(b)); comparator<card> result = (a, b) -> {   int res = comp1.compare(a, b);   return res != 0 ? res : comp2.compare(a, b); }; 

so after inlining (which might performed jit-compiler) may have this:

comparator<card> result = (a, b) -> {   int res = a.getrank().compareto(b.getrank());   return res != 0 ? res : a.getsuit().compareto(b.getsuit()); }; 

note can use simpler version:

mydeck.sort(     comparator         .comparing(card::getrank)         .thencomparing(card::getsuit)); 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -