From 8af39bf73021cd19aca167cef7e0cbf477ce316a Mon Sep 17 00:00:00 2001 From: gschambial Date: Wed, 29 Nov 2017 16:46:37 +0530 Subject: [PATCH] 1. Comparator example using Lambda and Comparator.comparing corrected. --- .../comparator/Java8ComparatorUnitTest.java | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java b/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java index b804573b51..49c8749309 100644 --- a/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java @@ -17,8 +17,8 @@ public class Java8ComparatorUnitTest { @Before public void setUp() { footballTeam = new ArrayList(); - 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 byRanking = new Comparator() { - - @Override - public int compare(Player player1, Player player2) { - return player1.getRanking() - player2.getRanking(); - } - }; + Comparator 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 byRanking = - (Player player1, Player player2)->player1.getRanking()-player2.getRanking(); + System.out.println("********* byRanking *********"); + Comparator 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 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); } }