Java/연습문제
자바 연습문제 - Comparator를 이용한 TreeSet 정렬 기준 지정
코딩하는냥이
2025. 5. 22. 15:47
반응형
📖 문제
TreeSet에 Student 객체를 저장할 때, score 필드값을 기준으로 자동 정렬되도록 하고 싶습니다.
이번에는 Student 클래스에서 Comparable을 구현하지 않고,
외부에서 Comparator를 이용해 정렬 기준을 제공하는 방식으로 구현해보세요.
📦 예제 클래스
Student.java
public class Student {
public String id;
public int score;
public Student (String id, int score) {
this.id = id;
this.score = score;
}
}
TreeSetExample.java
import java.util.TreeSet;
import java.util.Comparator;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.score > o2.score)
return 1;
else if (o1.score == o2.score)
return 0;
else
return -1;
}
});
treeSet.add(new Student("blue", 96));
treeSet.add(new Student("hong", 86));
treeSet.add(new Student("white", 92));
Student student = treeSet.last();
System.out.println("최고 점수 : " + student.score);
System.out.println("최고 점수를 받은 아이디 : " + student.id);
}
}
💻 실행 결과
최고 점수 : 96
최고 점수를 받은 아이디 : blue
💬 코드 설명
- Student 클래스에는 Comparable 구현이 전혀 없습니다.
- TreeSet 생성 시 정렬 기준을 익명 내부 클래스(Comparator)로 직접 제공합니다.
- compare() 메소드에서 score를 기준으로 비교해 정렬합니다.
- TreeSet.last() 호출 시 가장 높은 점수를 가진 객체가 반환됩니다.
💡 학습 포인트
- Comparator는 외부 정렬 기준 제공자 역할
내부 클래스를 수정하지 않고도 다양한 정렬 기준을 외부에서 유연하게 줄 수 있습니다. - 익명 클래스 vs 람다식
위 예제는 익명 클래스를 사용했지만, Java 8 이상에서는 아래와 같이 람다로 간결하게 표현할 수 있습니다: - TreeSet<Student> treeSet = new TreeSet<>( (s1, s2) -> Integer.compare(s1.score, s2.score) );
- 정렬 기준을 자유롭게 바꾸기 쉬움
Comparator를 사용하면 id 기준, score 내림차순 등 다양한 방식으로 정렬할 수 있습니다.
📌 마무리 정리
- Comparator 방식은 Student 클래스의 내부를 건드리지 않고도 정렬 기준을 외부에서 유연하게 지정할 수 있는 장점이 있습니다.
- TreeSet과 함께 사용할 경우, 생성자에서 직접 비교자를 넘겨주면 내부적으로 해당 기준에 따라 요소들이 자동 정렬됩니다.
- 랭킹이나 사용자 정의 기준 정렬이 필요한 실무 로직에서 자주 활용됩니다.