1. Introduction
Sutja moksuro jeongnyeolhal ttaeneun gan단합니다: sutja geu jachega bigyo hal gachi입니다. Hajiman hyeonsireul bogo iss-eumyeon data-ga bakkyeo bogo, geumse “category–sum”, “name–score”, “product–price”, “purchase–cost–comment” gateun bokjaphan hyeongtaero oneun gyeong-u-ga man습니다. Ije element-deul-eun “jachelo” jikjeop bigyohaego sip-eohaji ango, urineun gyeolgug mueos-eul gijun-euro jeongnyeolhalji gyeoljeonghaeya 합니다.
I “mueos” reul sorting key 라고 부릅니다: element-reul gajigo bigyo ganeunghan gachi(key) reul kkeonae(gyesanhae) geu key-ro jeongnyeol하는 것입니다. Kotlin-eun i reul wihayeo maeu pyeonlihan dogureul je공합니다: sortedBy 와 sortedByDescending.
Yesireul deureobomyeon, posang(deul) i deureo itneun sangja-ga 있고, 각 posang-e “weight” 라벨-i but-eo 있다고 haebos세요. Jeongnyeol-haneun daesang-eun sangja (list ui element) ijiman, bigyohagi pyeonhan geos-eun raebel-ui gachi (key) 입니다. Raebel-i weight-myeon weight-ro, raebel-i city-myeon city-ro jeongnyeol합니다.
2. Key-based sorting with sortedBy and sortedByDescending
Gajang jaju naneun sseunari-o bu터 si작해봅시다: list-ga 있고, geu element-deul-i “jachelo Comparable” il piryo-neun eopjiman, 각 element-es-eo bigyo ganeunghan gachi (sutja, munja-yeol, munja-yeol 길이) reul kkeonael su 있습니다. Kotlin yeonsan sortedBy { selector } 는 key selector 함수를 bad-a, key ui 오름차순으로 정렬된 새 list 를 반환합니다.
Ascending sort: sortedBy {...}
Meonjeo — uri projejteu eopsi, dongjak bangsig-eul bogi wihan jageun 예제입니다. Munja-yeol-eul 길이로 정렬합니다 (key-neun it.length):
fun main() {
val words = listOf("bbb", "a", "cc")
val sorted = words.sortedBy { it.length }
println(sorted) // [a, cc, bbb]
}
Ije i geos-eul silje app-e jeok-yonghaebopsida. Hyeonjae console expense tracker (ajik class eopsi) ui data model-eul dasi sangaekhaebomyeon: expense-neun Triple(category, amount, note) 입니다. category 와 note 는 string, amount 는 Int 입니다.
Modeun expense-reul amount-ro (oreumchaseun) jeongnyeolhaneun 코드는 다음과 같습니다:
fun main() {
val expenses = listOf(
Triple("food", 450, "coffee"),
Triple("taxi", 1200, "airport"),
Triple("food", 150, "snack")
)
val sortedByAmount = expenses.sortedBy { it.second }
println(sortedByAmount)
// [(food, 150, snack), (food, 450, coffee), (taxi, 1200, airport)]
}
Yeogiseo jungyohan geos-eun kodeu-reul “baro ilgi” 하는 것입니다: jeongnyeolhan daesang-eun Triple 자체이지만, bigyo-neun key 인 it.second, 즉 amount 로 합니다.
Descending sort: sortedByDescending {...}
Jom deo “silje” jeog-in beoryeon-eun 내림차순 정렬입니다: report 에서는 거의 항상 가장 큰 값을 위에서 보고 싶습니다. I ttae sayonghaneun 것이 sortedByDescending { selector } 입니다. Sorting key라는 같은 원리지만, 순서만 반대로 합니다.
Ye: gajang bi싼 purchase 를 위에 출력하고 싶다면:
fun main() {
val expenses = listOf(
Triple("food", 450, "coffee"),
Triple("taxi", 1200, "airport"),
Triple("books", 700, "kotlin book")
)
val sorted = expenses.sortedByDescending { it.second }
println(sorted)
// [(taxi, 1200, airport), (books, 700, kotlin book), (food, 450, coffee)]
}
Geuligo yeogiseo dangyeonhi daeum jilmuneun i geos입니다: “jeonche list 말고, cheos N개만 가져올 수 있나?” 가능합니다 — geugeo-ga baro jeontongjeog-in top‑N paeteon입니다.
3. Top‑N: sortedByDescending {...}.take(n) and why take without sorting is not “top”
Yogu-sahang-e “top‑3 category reul 보여줘” 라고 쓰여 있다면, 대개 뜻은 다음과 같습니다: metrik-euro 정렬하고 앞에서 세 개를 가져와라. Kotlin은 이를 한 체인으로 표현할 수 있습니다: sortedByDescending(...).take(n).
Hoksi he갈리지 ma세요: take(n) 은 choego ui element reul chajji anh습니다. Danji 현재 순서에서 앞의 n 개를 “잘라서” 가져옵니다. Geureomuro jeongnyeol eopsi “top‑N” 을 한다는 건, geunyeonhi “아무 순서로나 앞에서 N개” 를 가져온다는 뜻입니다.
Meonjeo 숫자 예제로 간단히 봅시다:
fun main() {
val scores = listOf(10, 70, 50, 20, 90)
val top3 = scores.sortedDescending().take(3)
println(top3) // [90, 70, 50]
}
Ije uri Triple format-e서 가장 비싼 expense top‑2 를 만들어 봅시다:
fun main() {
val expenses = listOf(
Triple("food", 450, "coffee"),
Triple("taxi", 1200, "airport"),
Triple("books", 700, "kotlin book"),
Triple("food", 150, "snack")
)
val top2 = expenses
.sortedByDescending { it.second }
.take(2)
println(top2)
// [(taxi, 1200, airport), (books, 700, kotlin book)]
}
Tto han 가지 좋은 점: element ga n 보다 적으면, take(n) 은 “있는 만큼만” 반환합니다. 예외도 없고, drama 도 없습니다.
4. Multiple criteria: sortedWith and compareBy
Maeu jaju naneun “il상” tareae: 여러 규칙으로 정렬하기. Ye를 들어, (category, total) pair list를 정렬하는데, 먼저 category 이름순(출력 예쁘게)으로, 그리고 이름이 같으면 두 번째 key로 total(또는 다른 값)을 쓰고 싶을 수 있습니다.
Yeoreo criterion sorting 은 folder 안의 document 정렬과 비슷합니다: 먼저 “Last name”, 같은 last name 안에서 “First name”, 같은 first name 안에서 “Date”. 한 가지 기준만으로는 부족해집니다.
Kotlin에서 “명시적인 비교 규칙을 줘야 하는 경우”에는 sortedWith(comparator)가 있고, comparator를 직접 쓰기 싫으면 comparator factory인 compareBy(...)가 있습니다. 보통은 이렇게 씁니다: sortedWith(compareBy {...}).
sortedWith(comparator): explicit rule로 정렬
sortedWith(...) 는 Comparator<T> 객체를 받아 새로 정렬된 list를 반환합니다. 다음 상황에서 유용합니다:
- element가 Comparable 이 아니거나,
- 여러 기준이 필요하거나,
- 비교 로직이 복잡한 경우 (예: “먼저 VIP, 그다음 amount”).
먼저 간단한 예: comparator로 string을 길이순 정렬:
fun main() {
val words = listOf("aaa", "bb", "c")
val sorted = words.sortedWith(compareBy { it.length })
println(sorted) // [c, bb, aaa]
}
Gisuljeok-euro-neun sortedBy { it.length } 와 비슷하지만, idea 가 다릅니다: “이게 비교 규칙이다”라고 명시합니다. 기준이 여러 개인 경우 특히 편합니다.
compareBy(...): one-key comparator
compareBy 는 이렇게 말하는 방법입니다: “이런 key들로 element를 비교하는 comparator를 만들어줘.” Comparator 내부 구현에 들어가지 않고, 완성품 도구처럼 씁니다.
Ye: expense(Triple)를 category 알파벳순으로 정렬:
fun main() {
val expenses = listOf(
Triple("taxi", 1200, "airport"),
Triple("food", 450, "coffee"),
Triple("books", 700, "kotlin book")
)
val sorted = expenses.sortedWith(compareBy { it.first })
println(sorted)
// [(books, 700, kotlin book), (food, 450, coffee), (taxi, 1200, airport)]
}
compareBy({ ... }, { ... }): multi-key comparator
compareBy 는 여러 selector를 받을 수 있고, 그러면 정렬은 다음처럼 진행됩니다: 먼저 첫 번째 key, 같으면 두 번째 key, 그리고 계속.
Pair (category, total) 예제로, 먼저 category name, 다음으로 total(오름차순)로 정렬해 봅시다:
fun main() {
val totals = listOf(
"food" to 200,
"taxi" to 250,
"food" to 150
)
val sorted = totals.sortedWith(
compareBy<Pair<String, Int>>({ it.first }, { it.second })
)
println(sorted) // [(food, 150), (food, 200), (taxi, 250)]
}
Yeogiseo Pair<String, Int> type-eul 명시한 이유는 compiler 와 reader 둘 다 편하게 하려고입니다. Type inference가 아직 익숙하지 않다면, type을 쓰는 걸 주저하지 마세요: “약함”이 아니라, 특히 밤 23:00에 mystic한 에러를 막는 보험입니다.
5. Mini integration: top‑N category report by sum
Ije 실제 feature와 매우 비슷한 mini scenario를 만들어 봅시다: category total을 담은 Map<String, Int> 가 있고, sum 기준으로 top‑N category를 출력하고 싶습니다.
아직은 groupBy 를 쓰지 않을 것이니(나중에 다룹니다), totalsByCategory 가 이미 앞의 코드에서 계산되어 있다고 가정합시다 (예: total 커맨드 handler). 이후는 정렬 메커닉만 남습니다.
Pipeline outline:
Map<String, Int>
→ entries
→ List<Pair<String, Int>>
→ sortedByDescending { sum }
→ take(n)
→ print
Code (읽기 좋게 작은 step으로 나눕니다):
fun main() {
val totalsByCategory = mapOf(
"food" to 1200,
"taxi" to 2500,
"books" to 900
)
val topN = 2
val pairs = totalsByCategory.entries.map { it.key to it.value }
val top = pairs.sortedByDescending { it.second }.take(topN)
println(top) // [(taxi, 2500), (food, 1200)]
}
Yeogiseo 두 가지가 특히 중요합니다.
Cheot째, Map 을 그대로 정렬하는 게 아니라, entries를 pair list로 바꾼 다음 정렬합니다. 이는 일반적인 실무 패턴입니다: sorting은 sequence(list)에 대한 연산이고, Map 은 “key로 접근”이 핵심이기 때문입니다.
Dul째, top‑N 은 반드시 이 순서입니다: 먼저 sorting, 그다음 앞에서 n 개 take. 순서를 바꾸면 “Map 내부 순서에서 앞의 N개”가 되어버리는데, 그건 거의 절대 top이 아닙니다(가끔 우연히 맞을 수 있지만, 그런 우연은 나중에 신뢰를 망가뜨립니다).
6. How to choose the tool and how to read sortedBy
Eotteon sungan students-ga 묻기 시작합니다: “sortedBy 가 좋아요, 아니면 sortedWith(compareBy(...)) 가 좋아요?” 자연스러운 질문입니다: 둘 다 종종 비슷해 보입니다.
아래 작은 표로 선택을 정리해 봅시다:
| Task | What to write | Why |
|---|---|---|
| One simple key, ascending | |
가장 짧고 읽기 쉬운 선택. |
| One simple key, descending | |
원리는 같고, 단지 “큰 것부터”. |
| Multiple criteria | |
기준들과 적용 순서가 명확히 보임. |
| Custom comparison rule | |
비교 로직을 직접 설명해야 할 때. |
Jageun “human rule” 하나: key가 하나면 sortedBy 를 쓰세요. 기준이 여러 개면, 대개 sortedWith(compareBy(...)) 가 더 잘 읽히고 확장도 편합니다.
Majimak-e, jaju saenggineun hegal림을 바로 짚고 갑시다. sortedBy {...} 안에서 lambda의 it 는 list element 이고, lambda 결과는 sorting key 입니다.
사람들이 자주 헷갈리는 예 (특히 Pair 가 짧아서):
fun main() {
val totals = listOf("food" to 1200, "taxi" to 2500)
val sorted = totals.sortedBy { it.second }
println(sorted) // [(food, 1200), (taxi, 2500)]
}
it 는 pair (String, Int) 이고, it.second 는 Int, 즉 sorting key 입니다. Pair를 정렬하지만, 비교하는 값은 number 입니다.
Mankeum “내가 pair list를 두고 왜 Int 를 정렬하지?” 라는 생각이 들었다면, 오히려 잘 하고 있는 겁니다: sorting key를 인지했다는 뜻이니까요.
7. Common mistakes
Mistake №1: using take(n) without sorting and calling it “top‑N”.
take(n) 은 “best를 선택”이 아니라 “앞에서 n개를 자르기”입니다. 원래 순서가 insertion order라면, 결과는 “먼저 추가된 것들”이지 “가장 큰 것들”이 아닙니다. Fix는 거의 항상 하나: 먼저 metric으로 sorting, 그다음 take.
Mistake №2: sorting by the wrong key (mixing up first/second/third).
Data를 Pair/Triple 로 저장하면, 매우 쉽게 잘못된 field로 정렬하게 되고 몇 분 동안 결과를 보며 “프로그램이 나를 놀리나?” 같은 기분이 들 수 있습니다. 도움이 되는 습관: 정렬하기 전에 머릿속에서 field 의미를 말로 붙이기(“first=category, second=amount”), 그리고 코드에서는 임시로 몇 개 element를 출력해 검증하기.
Mistake №3: trying to sort a Map “as is” and then being surprised.
Map 은 list가 아닙니다; 핵심은 순서가 아니라 key로 access 하는 것입니다. Sorting을 하려면 거의 항상 entries.map { ... } 으로 list를 만든 다음, 그 list를 정렬합니다. 이건 hack가 아니라 목적에 맞게 container를 변환하는 정상적인 과정입니다.
Mistake №4: cramming multiple criteria into one “monstrous” lambda.
기준이 2~3개일 때, 초보자는 종종 sortedWith { a, b -> ... } 안에 온갖 비교를 뒤섞어서 쓰고, 괄호는 제멋대로 살고, 전체가 주문처럼 보이게 만듭니다. 대부분의 경우 sortedWith(compareBy({ ... }, { ... })) 가 더 읽기 쉽고 안전합니다. Key 적용 순서가 그대로 드러나기 때문입니다.
Mistake №5: “losing” the sorting result.
sortedBy 와 sortedWith 같은 sorting 함수는 새로운 list를 반환하고, 원본은 바꾸지 않습니다. expenses.sortedBy { it.second } 라고 써 놓고 다음에 expenses 를 출력하면, “마법처럼” 아무 일도 일어나지 않습니다. 해결은 간단합니다: 결과를 val 에 담거나, 체인을 바로 이어 쓰세요 (예: sortedByDescending { ... }.take(3)), 위에서 했던 것처럼요.
GO TO FULL VERSION