Skip to content

Commit e6ad051

Browse files
author
frankyoh
committed
[TUT-39] 정렬 sore -> name으로 정렬하기
1 parent 059b6e5 commit e6ad051

3 files changed

Lines changed: 31 additions & 2 deletions

File tree

java-compare/src/main/java/com/advenoh/model/ComparablePlayer.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff 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
}

java-compare/src/main/java/com/advenoh/model/ComparatorPlayer.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,12 @@
1010
public 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
}

java-compare/src/test/java/com/advenoh/CompareTest.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import com.advenoh.model.ComparablePlayer;
44
import com.advenoh.model.ComparatorPlayer;
5+
import lombok.extern.slf4j.Slf4j;
56
import org.junit.Before;
67
import org.junit.Test;
78

@@ -13,6 +14,7 @@
1314

1415
import static org.assertj.core.api.Assertions.assertThat;
1516

17+
@Slf4j
1618
public 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
}

0 commit comments

Comments
 (0)