JAVA · 컬렉션
Comparator 심화
Comparator의 팩토리 메서드와 체이닝으로 복잡한 정렬을 구현합니다.
컬렉션중급Comparator정렬comparingthenComparing
핵심 설명
Comparator의 팩토리 메서드와 체이닝으로 복잡한 정렬을 구현합니다.
Java code
import java.util.*;
public class ComparatorAdvanced {
record Student(String name, int grade, double score) {}
public static void main(String[] args) {
List<Student> students = new ArrayList<>(List.of(
new Student("홍길동", 3, 85.5),
new Student("김철수", 1, 92.0),
new Student("이영희", 2, 85.5),
new Student("박민수", 1, 88.0)
));
// 단일 기준 정렬
students.sort(Comparator.comparing(Student::name));
// 다중 기준: 점수 내림차순 -> 학년 오름차순 -> 이름
Comparator<Student> comp = Comparator
.comparingDouble(Student::score).reversed()
.thenComparingInt(Student::grade)
.thenComparing(Student::name);
students.sort(comp);
students.forEach(s -> System.out.printf(
"%s (학년:%d, 점수:%.1f)%n", s.name(), s.grade(), s.score()));
// null 안전 정렬
List<String> withNull = new ArrayList<>(
Arrays.asList("B", null, "A", null, "C"));
withNull.sort(Comparator.nullsLast(Comparator.naturalOrder()));
System.out.println(withNull); // [A, B, C, null, null]
}
}학습 팁
Comparator.comparing()에 원시 타입 특화 버전(comparingInt, comparingDouble)을 사용하면 오토박싱을 방지합니다.
주의할 점
Comparator에서 뺄셈(a - b)으로 비교하면 오버플로우가 발생할 수 있습니다. Integer.compare()를 사용하세요.
자주 묻는 질문
Comparator 심화란 무엇인가요?
Comparator 의 팩토리 메서드와 체이닝으로 복잡한 정렬을 구현합니다.
Comparator 심화 학습 시 주의할 점은 무엇인가요?
Comparator 에서 뺄셈( a - b )으로 비교하면 오버플로우가 발생할 수 있습니다. Integer.compare() 를 사용하세요.
Continue Learning
Java 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.