@@ -17,24 +17,18 @@ public class Java8ComparatorUnitTest {
17
17
@ Before
18
18
public void setUp () {
19
19
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 );
22
22
Player player3 = new Player (45 , "Steven" , 24 );
23
23
footballTeam .add (player1 );
24
24
footballTeam .add (player2 );
25
25
footballTeam .add (player3 );
26
26
}
27
27
28
28
@ Test
29
- public void whenComparing_UsingJava8_thenSorted () {
29
+ public void whenComparing_UsingLambda_thenSorted () {
30
30
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 ();
38
32
39
33
System .out .println ("Before Sorting : " + footballTeam );
40
34
Collections .sort (footballTeam , byRanking );
@@ -48,8 +42,8 @@ public int compare(Player player1, Player player2) {
48
42
@ Test
49
43
public void whenComparing_UsingComparatorComparing_thenSorted () {
50
44
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 );
53
47
54
48
System .out .println ("Before Sorting : " + footballTeam );
55
49
Collections .sort (footballTeam , byRanking );
@@ -58,6 +52,17 @@ public void whenComparing_UsingComparatorComparing_thenSorted() {
58
52
.getName (), "Steven" );
59
53
assertEquals (footballTeam .get (2 )
60
54
.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 );
61
66
}
62
67
63
68
}
0 commit comments