- 코드상 리스트를 TreeSet에 넣어 기존 Set 처럼 중복된 데이터는 제거하면서 정렬까지 진행되는 것을 확인할 수 있다.
List<Integer> scores = List.of(10, 27, 3, 11, 1, 11)
Set<Integer> newScores = new TreeSet<>(scores);
System.out.println(newScores)
- 다만 문자열의 경우, 사전순으로 정렬되기 때문에 원하는 결과가 나오지 않는 경우가 있다.
List<String> scores = List.of("10번", "27번", "3번", "11번", "1번", "11번")
Set<String> newScores = new TreeSet<>(scores);
System.out.println(newScores)
- 이를 해결하기 위해
Comparator을 도입하여 원하는 순서로 정렬이 이루어질 수 있도록 한다.Comparator<String> comparator = (s1, s2) -> {
Integer idx1 = Integer.parseInt(s1.split("번")[0]);
Integer idx2 = Integer.parseInt(s2.split("번")[0]);
return idx1.compareTo(idx2);
};
List<String> scores = List.of("10번", "27번", "3번", "11번", "1번", "11번")
Set<String> newScores = new TreeSet<>(comparator);
answers.addAll(scores);
System.out.println(newScores)