1. Comparator example using Lambda and Comparator.comparing corrected.

This commit is contained in:
gschambial 2017-11-29 16:46:37 +05:30
parent 352af1c6c5
commit 8af39bf730
1 changed files with 17 additions and 12 deletions

View File

@ -17,8 +17,8 @@ public class Java8ComparatorUnitTest {
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
@ -26,15 +26,9 @@ public class Java8ComparatorUnitTest {
}
@Test
public void whenComparing_UsingJava8_thenSorted() {
public void whenComparing_UsingLambda_thenSorted() {
System.out.println("************** Java 8 Comaparator **************");
Comparator<Player> byRanking = new Comparator<Player>() {
@Override
public int compare(Player player1, Player player2) {
return player1.getRanking() - player2.getRanking();
}
};
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
@ -48,8 +42,8 @@ public class Java8ComparatorUnitTest {
@Test
public void whenComparing_UsingComparatorComparing_thenSorted() {
System.out.println("********* Comaparator.comparing method *********");
Comparator<Player> byRanking =
(Player player1, Player player2)->player1.getRanking()-player2.getRanking();
System.out.println("********* byRanking *********");
Comparator<Player> byRanking = Comparator.comparing(Player::getRanking);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
@ -58,6 +52,17 @@ public class Java8ComparatorUnitTest {
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
System.out.println("********* byAge *********");
Comparator<Player> byAge = Comparator.comparing(Player::getAge);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byAge);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Roger");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}