Java에서의 정렬 방법
Java에서 객체를 정렬하는 방법은 크게 Comparable, Comparator, 그리고 람다식을 활용한 방식으로 나눌 수 있다. 각각의 특징과 사용 방법을 정리해보자.
1. Comparable을 이용한 정렬
Comparable은 객체 자체의 기본 정렬 기준을 정의할 때 사용한다. 클래스에 직접 구현하며 compareTo() 메서드를 오버라이딩해야 한다.
✔ 기본 구조
class Student implements Comparable<Student> {
int idx, height, weight;
Student(int idx, int height, int weight) {
this.idx = idx;
this.height = height;
this.weight = weight;
}
@Override
public int compareTo(Student o) {
return this.height - o.height; // 오름차순
}
}
✔ 오름차순 / 내림차순
- 오름차순:
this - o - 내림차순:
o - this
// 내림차순 (키 기준)
return o.height - this.height;
✔ 다중 조건 정렬
여러 기준으로 정렬할 경우, 조건을 순차적으로 비교한다.
@Override
public int compareTo(Student o) {
if (o.height != this.height)
return o.height - this.height; // 키 내림차순
else if (o.weight != this.weight)
return o.weight - this.weight; // 몸무게 내림차순
return this.idx - o.idx; // idx 오름차순
}
✔ 특징
- 클래스 자체에 정렬 기준을 포함
Collections.sort()또는Arrays.sort()에서 자동 사용됨- 기본 정렬 기준 1개만 정의 가능
2. Comparator를 이용한 정렬
Comparator는 외부에서 정렬 기준을 정의할 때 사용한다. 즉, 같은 클래스라도 다양한 기준으로 정렬 가능하다.
✔ 기본 구조
class Student implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.height - o2.height;
}
}
✔ 오름차순 / 내림차순
// 오름차순
return o1.height - o2.height;
// 내림차순
return o2.height - o1.height;
✔ 다중 조건 정렬
@Override
public int compare(Student o1, Student o2) {
if (o2.height != o1.height)
return o2.height - o1.height;
else if (o2.weight != o1.weight)
return o2.weight - o1.weight;
return o1.idx - o2.idx;
}
✔ 사용 방법
Arrays.sort(arr, new Student());
3. 람다식을 이용한 정렬
Java 8 이후부터는 Comparator를 람다식으로 간단하게 표현할 수 있다.
✔ 기본 형태
Arrays.sort(arr, (o1, o2) -> o1.height - o2.height);
✔ 다중 조건 정렬
Arrays.sort(arr, (o1, o2) -> {
if (o1.height != o2.height)
return o2.height - o1.height;
else if (o1.weight != o2.weight)
return o2.weight - o1.weight;
return o1.idx - o2.idx;
});
4. Comparable vs Comparator 차이점
| 구분 | Comparable | Comparator |
|---|---|---|
| 위치 | 클래스 내부 | 클래스 외부 |
| 메서드 | compareTo() | compare() |
| 정렬 기준 | 1개 (기본 정렬) | 여러 개 가능 |
| 유연성 | 낮음 | 높음 |
| 사용 시점 | 기본 정렬 필요 시 | 다양한 정렬 기준 필요 시 |
✔ 정리
- Comparable: 기본 정렬 기준 정의 (한 가지 기준)
- Comparator: 다양한 정렬 기준 정의 가능
- 람다식: Comparator를 간결하게 표현하는 최신 방식
'알고리즘' 카테고리의 다른 글
| [MySQL] 자주 쓰이는 함수 정리 (0) | 2026.03.27 |
|---|---|
| [백준 - G3] 20057. 마법사 상어와 토네이도 (0) | 2026.03.26 |
| [백준 - G5] 17836. 공주님을 구해라! (0) | 2026.03.04 |
| [백준 - S4] 1059. 좋은 구간 (0) | 2026.02.13 |
| [백준 - G4] 15685. 드래곤 커브 (0) | 2026.01.31 |