KOTLIN · 컬렉션
정렬 심화 (Advanced Sorting)
다양한 정렬 기준과 커스텀 비교자를 활용합니다. sortedBy, sortedWith, compareBy를 다룹니다.
컬렉션중급sortingcompareBysortedWithcomparator
핵심 설명
다양한 정렬 기준과 커스텀 비교자를 활용합니다. sortedBy, sortedWith, compareBy를 다룹니다.
Kotlin code
data class Student(val name: String, val grade: Int, val score: Double)
fun main() {
val students = listOf(
Student("김철수", 3, 88.5),
Student("이영희", 2, 92.0),
Student("박지성", 3, 88.5),
Student("최유리", 1, 95.0),
Student("정민호", 2, 87.3),
)
// 단일 기준 정렬
println(students.sortedBy { it.score })
// 다중 기준: 학년 오름차순 → 점수 내림차순
val sorted = students.sortedWith(
compareBy<Student> { it.grade }
.thenByDescending { it.score }
)
sorted.forEach { println("${it.grade}학년 ${it.name}: ${it.score}") }
// 커스텀 Comparator
val byNameLength = Comparator<Student> { a, b ->
a.name.length - b.name.length
}
println(students.sortedWith(byNameLength).map { it.name })
// 안정 정렬 확인
val stable = students.sortedBy { it.score }
println(stable.filter { it.score == 88.5 }.map { it.name })
}학습 팁
Kotlin의 정렬은 안정 정렬(stable sort)입니다. 같은 값의 원소 순서가 보존되므로 다단계 정렬을 순차적으로 적용해도 안전합니다.
주의할 점
sortedBy는 새 리스트를 반환하고, sortBy는 MutableList를 제자리 정렬합니다. 불변 리스트에 sortBy를 쓸 수 없습니다.
자주 묻는 질문
정렬 심화 (Advanced Sorting)란 무엇인가요?
다양한 정렬 기준과 커스텀 비교자를 활용합니다. sortedBy , sortedWith , compareBy 를 다룹니다.
정렬 심화 (Advanced Sorting) 학습 시 주의할 점은 무엇인가요?
sortedBy 는 새 리스트를 반환하고, sortBy 는 MutableList를 제자리 정렬합니다. 불변 리스트에 sortBy 를 쓸 수 없습니다.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.