---
id: java-advanced-sorting
title: "Java Advanced Sorting"
category: "Programming_Language"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Comparator", "Comparable", "자바 고급 정렬"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-07-04
updated_at: 2026-07-04
review_reason: ""
merge_history: []
tags: ["java", "programming", "w3schools", "sorting", "comparator", "comparable"]
raw_sources: ["https://www.w3schools.com/java/java_advanced_sorting.asp"]
applied_in: []
github_commit: ""
---

# [[Java Advanced Sorting]]

## 🎯 한 줄 통찰 (One-line insight)
`a.year - b.year` is a one-line replacement for the verbose `if/else if/else` comparison ladder — and simply flipping it to `b.year - a.year` reverses the sort order, a trick that works specifically because subtraction naturally encodes negative/positive/zero the same way `compare()`/`compareTo()` are required to. [S1]

## 🧠 핵심 개념 (Core concepts)
- **Problem**: `Collections.sort()` alone can't sort custom objects — you need a rule for what "comes first." [S1]
- **`Comparator` interface** — external comparison logic via `compare(obj1, obj2)`: negative (first goes first), positive (second goes first), zero (order doesn't matter). [S1]
- **`Comparable` interface** — the object compares ITSELF via `compareTo(obj)`, same return-value convention. [S1]
- **Native Comparable classes** — `String` and `Integer` already implement Comparable, which is why they sort without a custom comparator. [S1]
- **Lambda as comparator** — replaces a full Comparator class with an inline lambda matching `compare()`'s signature. [S1]
- **Subtraction trick** — `return a.year - b.year;` replaces the if/else ladder; `b.year - a.year` reverses it. [S1]
- **Comparator vs. Comparable** — Comparator: external, can sort any object (even ones you can't modify); Comparable: built into the object itself, simpler when you control the class. [S1]

## 📖 세부 내용 (Details)
- Comparator class: `class SortByYear implements Comparator { public int compare(Object obj1, Object obj2) { Car a = (Car) obj1; Car b = (Car) obj2; if (a.year < b.year) return -1; if (a.year > b.year) return 1; return 0; } } ... Collections.sort(myCars, new SortByYear());`. [S1]
- Lambda comparator: `Collections.sort(myCars, (obj1, obj2) -> { Car a = (Car) obj1; Car b = (Car) obj2; if (a.year < b.year) return -1; if (a.year > b.year) return 1; return 0; });`. [S1]
- Custom rule (even-first): `class SortEvenFirst implements Comparator { ... boolean aIsEven = (a % 2) == 0; ... }`. [S1]
- Comparable: `class Car implements Comparable { public int compareTo(Object obj) { Car other = (Car)obj; if(year < other.year) return -1; if(year > other.year) return 1; return 0; } } ... Collections.sort(myCars); // no comparator needed`. [S1]
- Subtraction shortcut: `return a.year - b.year;` (ascending) or `return b.year - a.year;` (descending). [S1]

## ⚖️ 모순 및 업데이트 (Contradictions & updates)
소스에서 모순되는 정보는 발견되지 않음.

## 🛠️ 적용 사례 (Applied in summary)
현재 발견된 실제 적용 사례가 없습니다 — 자동차 객체를 연도순으로 정렬하는 예제(Comparator/Comparable 두 방식 모두)가 커스텀 객체 정렬의 대표 사례다. [S1]

## 💻 코드 패턴 (Code patterns)
Subtraction shortcut for numeric comparison (Java):
```java
// Instead of:
// if(a.year < b.year) return -1;
// if(a.year > b.year) return 1;
// return 0;
return a.year - b.year;   // ascending
return b.year - a.year;   // descending
```

## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)

## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[Java Tutorial]]
- **관련 개념:** [[Java Sort List]], [[Java Lambda]], [[Java Algorithms]], [[Java Projects]]
- **참조 맥락:** 커스텀 객체 정렬 — 람다 표현식 활용의 실전 사례. Projects 챕터로 이어짐(Java 튜토리얼 최종).

## 📚 출처 (Sources)
- [S1] W3Schools — Java Advanced Sorting (Comparator and Comparable) — https://www.w3schools.com/java/java_advanced_sorting.asp

## 📝 변경 이력 (Change history)
- 2026-07-04: Initial draft synthesized from the W3Schools "Java Advanced Sorting" page (Astra wiki-curation, P-Reinforce v3.1 format).
