File tree Expand file tree Collapse file tree
main/java/com/advenoh/model Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -11,7 +11,8 @@ public class ComparablePlayer implements Comparable<ComparablePlayer> {
1111 private String name ;
1212 private int score ;
1313
14- @ Override public int compareTo (ComparablePlayer o ) {
15- return o .getScore () - getScore ();
14+ @ Override
15+ public int compareTo (ComparablePlayer o ) {
16+ return o .getScore () - this .getScore ();
1617 }
1718}
Original file line number Diff line number Diff line change 1010public class ComparatorPlayer {
1111 private String name ;
1212 private int score ;
13+
14+ public static int compareByScoreThenName (ComparatorPlayer lhs , ComparatorPlayer rhs ) {
15+ if (lhs .getScore () == rhs .getScore ()) {
16+ return lhs .getName ().compareTo (rhs .getName ());
17+ } else {
18+ return lhs .getScore () - rhs .getScore ();
19+ }
20+ }
1321}
Original file line number Diff line number Diff line change 22
33import com .advenoh .model .ComparablePlayer ;
44import com .advenoh .model .ComparatorPlayer ;
5+ import lombok .extern .slf4j .Slf4j ;
56import org .junit .Before ;
67import org .junit .Test ;
78
1314
1415import static org .assertj .core .api .Assertions .assertThat ;
1516
17+ @ Slf4j
1618public class CompareTest {
1719 List <ComparablePlayer > comparablePlayers ;
1820
@@ -65,4 +67,22 @@ public void streamComparableSort() {
6567
6668 assertThat (sortedPlayers ).isSorted ();
6769 }
70+
71+ @ Test
72+ public void sortByScoreThenName () {
73+ List <ComparatorPlayer > players = new ArrayList <>();
74+ players .add (new ComparatorPlayer ("Chloe" , 1090 ));
75+ players .add (new ComparatorPlayer ("Dale" , 982 ));
76+ players .add (new ComparatorPlayer ("Alice" , 899 ));
77+ players .add (new ComparatorPlayer ("Bob" , 982 ));
78+ players .add (new ComparatorPlayer ("Eric" , 1018 ));
79+
80+ List <ComparatorPlayer > sortedPlayers = players .stream ()
81+ //.sorted((a, b) -> ComparatorPlayer.compareByNameThenScore(a, b))
82+ .sorted (ComparatorPlayer ::compareByScoreThenName )
83+ .collect (Collectors .toList ());
84+
85+ assertThat (sortedPlayers ).isSortedAccordingTo (ComparatorPlayer ::compareByScoreThenName );
86+
87+ }
6888}
You can’t perform that action at this time.
0 commit comments