11package com .rakitov .sandbox .comparators2 ;
22
33import java .util .ArrayList ;
4+ import java .util .Collections ;
45import java .util .Comparator ;
56import java .util .List ;
67
@@ -14,13 +15,37 @@ public static void main(String[] args) {
1415 women .add (new Woman ("Kate" , 34 , 168 , 67 , 2 ));
1516 women .add (new Woman ("Jackie" , 44 , 183 , 57 , 1 ));
1617
18+ // Anonymous new Comparator<Woman>() can be replaced with lambda
19+ Comparator <Woman > compareByName = new Comparator <Woman >() {
20+ @ Override
21+ public int compare (Woman w1 , Woman w2 ) {
22+ return w1 .getName ().compareTo (w2 .getName ());
23+ }
24+ };
25+ // Like this, but it Can be replaced with 'Comparator.comparing'
26+ Comparator <Woman > compareByNameLambda = (w1 , w2 ) -> w1 .getName ().compareTo (w2 .getName ());
27+ // Can be replaced with 'Comparator.comparing'
28+ Comparator <Woman > compareByNameComparator = Comparator .comparing (Woman ::getName );
1729
18- Comparator <Woman > compareByHeight = Comparator .comparingInt (Woman ::getHeight );
30+
31+ // Lambda can be replaced with method reference
32+ Comparator <Woman > compareByHeight = Comparator .comparingInt (woman -> woman .getHeight ());
1933
2034 System .out .println ("Before sort" );
2135 women .forEach (System .out ::println );
22- System .out .println ("\n After sort" );
23- women .sort (compareByHeight );
36+ System .out .println ("\n After sort height" );
37+
38+ // Collections.sort could be replaced with List.sort
39+ Collections .sort (women , compareByHeight );
40+ women .forEach (System .out ::println );
41+ System .out .println ("\n After sort weight" );
42+ // Can sort like this too.
43+ // and another way to make a comparator
44+ women .sort (Comparator .comparingInt (Woman ::getWeight ));
45+ women .forEach (System .out ::println );
46+
47+ System .out .println ("\n After name sort" );
48+ women .sort (compareByName );
2449 women .forEach (System .out ::println );
2550
2651 }
0 commit comments