@@ -17,24 +17,18 @@ public class Java8ComparatorUnitTest {
1717 @ Before
1818 public void setUp () {
1919 footballTeam = new ArrayList <Player >();
20- Player player1 = new Player (59 , "John" , 20 );
21- Player player2 = new Player (67 , "Roger" , 22 );
20+ Player player1 = new Player (59 , "John" , 22 );
21+ Player player2 = new Player (67 , "Roger" , 20 );
2222 Player player3 = new Player (45 , "Steven" , 24 );
2323 footballTeam .add (player1 );
2424 footballTeam .add (player2 );
2525 footballTeam .add (player3 );
2626 }
2727
2828 @ Test
29- public void whenComparing_UsingJava8_thenSorted () {
29+ public void whenComparing_UsingLambda_thenSorted () {
3030 System .out .println ("************** Java 8 Comaparator **************" );
31- Comparator <Player > byRanking = new Comparator <Player >() {
32-
33- @ Override
34- public int compare (Player player1 , Player player2 ) {
35- return player1 .getRanking () - player2 .getRanking ();
36- }
37- };
31+ Comparator <Player > byRanking = (Player player1 , Player player2 ) -> player1 .getRanking () - player2 .getRanking ();
3832
3933 System .out .println ("Before Sorting : " + footballTeam );
4034 Collections .sort (footballTeam , byRanking );
@@ -48,8 +42,8 @@ public int compare(Player player1, Player player2) {
4842 @ Test
4943 public void whenComparing_UsingComparatorComparing_thenSorted () {
5044 System .out .println ("********* Comaparator.comparing method *********" );
51- Comparator < Player > byRanking =
52- ( Player player1 , Player player2 )-> player1 . getRanking ()- player2 . getRanking ( );
45+ System . out . println ( "********* byRanking *********" );
46+ Comparator < Player > byRanking = Comparator . comparing ( Player :: getRanking );
5347
5448 System .out .println ("Before Sorting : " + footballTeam );
5549 Collections .sort (footballTeam , byRanking );
@@ -58,6 +52,17 @@ public void whenComparing_UsingComparatorComparing_thenSorted() {
5852 .getName (), "Steven" );
5953 assertEquals (footballTeam .get (2 )
6054 .getRanking (), 67 );
55+
56+ System .out .println ("********* byAge *********" );
57+ Comparator <Player > byAge = Comparator .comparing (Player ::getAge );
58+
59+ System .out .println ("Before Sorting : " + footballTeam );
60+ Collections .sort (footballTeam , byAge );
61+ System .out .println ("After Sorting : " + footballTeam );
62+ assertEquals (footballTeam .get (0 )
63+ .getName (), "Roger" );
64+ assertEquals (footballTeam .get (2 )
65+ .getRanking (), 45 );
6166 }
6267
6368}
0 commit comments