✔ 컬렉션 관련
- map
- filter
- sortedBy, sortedByDescending
- groupBy
- distinctBy
- any, all
- fold, reduce
- associateBy, associate
- take, drop
- zip
✔ 스코프 함수
- let
- run
- apply
- also
- with
✔ null 처리 관련
- ?:, ?., !!
- takeIf, takeUnless
- ifEmpty, ifBlank
1. 컬렉션(Collection) 메서드 예시
1) map — 리스트 변환
val nums = listOf(1, 2, 3)
val result = nums.map { it * 2 }
println(result)
출력 → [2, 4, 6]
2) filter — 조건에 맞는 것만 추리기
val nums = listOf(1, 2, 3, 4, 5)
val result = nums.filter { it % 2 == 0 }
println(result)
출력 → [2, 4]
3) sortedBy / sortedByDescending — 정렬
val users = listOf(
User(1, "A"),
User(3, "C"),
User(2, "B")
)
val asc = users.sortedBy { it.id }
val desc = users.sortedByDescending { it.id }
println(asc.map { it.id })
println(desc.map { it.id })
출력 →
asc → [1, 2, 3]
desc → [3, 2, 1]
4) groupBy — 그룹으로 묶기
val nums = listOf(1, 2, 3, 4, 5, 6)
val grouped = nums.groupBy { it % 2 }
println(grouped)
출력 →
{1=[1, 3, 5], 0=[2, 4, 6]}
(1=홀수, 0=짝수)
5) distinctBy — 특정 값을 기준으로 중복 제거
val users = listOf(
User(1, "A"),
User(1, "Duplicate"),
User(2, "B")
)
val result = users.distinctBy { it.id }
println(result)
출력 →
[User(id=1, name=A), User(id=2, name=B)]
6) any / all — 조건 검사
val nums = listOf(1, 2, 3, 4)
println(nums.any { it > 3 }) // 하나라도 3보다 큰가?
println(nums.all { it > 0 }) // 모두 0보다 큰가?
출력 →
true
true
7) fold / reduce — 누적 계산
fold (초기값 있음)
val sum = listOf(1, 2, 3).fold(0) { acc, n -> acc + n }
println(sum)
출력 → 6
*또다른 예시
val list = listOf(1, 2, 3)
val sumFold = list.fold(0) { acc, n ->
println("fold - acc = $acc, n = $n -> next = ${acc + n}")
acc + n
}
println("fold result = $sumFold")
동작 흐름 (실제 콘솔 출력)
fold - acc = 0, n = 1 -> next = 1
fold - acc = 1, n = 2 -> next = 3
fold - acc = 3, n = 3 -> next = 6
fold result = 6
설명
- 초기값 acc = 0 으로 시작.
- 1번째 반복: acc=0, n=1 → acc+n=1 (다음 acc)
- 2번째 반복: acc=1, n=2 → acc+n=3
- 3번째 반복: acc=3, n=3 → acc+n=6
- 최종 결과 6 반환.
fold는 초기값(여기선 0) 을 사용해 왼쪽부터 순서대로 누적한다.
reduce (초기값 = 첫 요소)
val sum = listOf(1, 2, 3).reduce { acc, n -> acc + n }
println(sum)
출력 → 6
*또다른 예시
val list = listOf(1, 2, 3)
val sumReduce = list.reduce { acc, n ->
println("reduce - acc = $acc, n = $n -> next = ${acc + n}")
acc + n
}
println("reduce result = $sumReduce")
동작 흐름 (실제 콘솔 출력)
reduce - acc = 1, n = 2 -> next = 3
reduce - acc = 3, n = 3 -> next = 6
reduce result = 6
설명
- reduce는 첫 번째 요소를 초기 acc로 사용한다. 여기서 첫 요소는 1.
- 1번째 호출(실제 첫 lambda 호출)은 acc=1(첫 요소), n=2(두번째 요소) → 1+2=3
- 2번째 호출: acc=3, n=3 → 3+3=6
- 최종 6 반환.
주의: reduce는 첫 요소를 이미 소비해서, lambda는 list.size - 1번 호출된다.
8) associateBy / associate — Map 만들기
associateBy
val users = listOf(User(1, "A"), User(2, "B"))
val map = users.associateBy { it.id }
println(map)
출력 →
{1=User(1, A), 2=User(2, B)}
associate
val map2 = users.associate { it.id to it.name }
println(map2)
출력 →
{1=A, 2=B}
9) take / drop — 일정 개수 가져오기 / 버리기
val nums = listOf(1, 2, 3, 4, 5)
println(nums.take(3))
println(nums.drop(2))
출력 →
[1, 2, 3]
[3, 4, 5]
10) zip — 두 리스트 병합
val names = listOf("A", "B", "C")
val ages = listOf(10, 20, 30)
val pairs = names.zip(ages)
println(pairs)
출력 →
[(A, 10), (B, 20), (C, 30)]
2. 스코프 함수 예시
11) let — null 체크 / 변환
val name: String? = "Tom"
val len = name?.let { it.length }
println(len)
출력 → 3
12) run — 여러 작업을 묶어 결과 반환
val user = User(1, "Tom")
val text = user.run { "$name ($id)" }
println(text)
출력 →
Tom (1)
13) apply — 객체 초기화
val user = UserMutable().apply {
id = 1
name = "Tom"
}
println("${user.id}, ${user.name}")
출력 →
1, Tom
14) also — 부가 작업 (로그·디버깅)
val list = mutableListOf(1, 2).also { println("현재: $it") }
list.add(3)
println(list)
출력 →
현재: [1, 2]
[1, 2, 3]
15) with — 특정 객체 여러 번 사용
val user = User(1, "Tom")
with(user) {
println(id)
println(name)
}
출력 →
1
Tom
3. Null 관련 문법 예시
16) ?: — null이면 기본값
val name: String? = null
val display = name ?: "Unknown"
println(display)
출력 → Unknown
17) ?. — null-safe 호출
val name: String? = "Tom"
println(name?.uppercase())
출력 → TOM
18) !! — null이면 NPE 터뜨림
val name: String? = null
println(name!!.length) // 실행 시 오류
19) takeIf — 조건 맞으면 값, 아니면 null
val num = 10
val result = num.takeIf { it > 5 }
println(result)
출력 → 10
val result2 = num.takeIf { it > 20 }
println(result2)
출력 → null
20) ifEmpty / ifBlank
val text = ""
println(text.ifBlank { "EMPTY" })
출력 → "EMPTY"
val list = emptyList<Int>()
println(list.ifEmpty { listOf(99) })
출력 → [99]
반응형
'코딩테스트' 카테고리의 다른 글
| [프로그래머스] 배열의 평균값 (0) | 2025.12.19 |
|---|---|
| [프로그래머스] 배열 뒤집기 (0) | 2025.12.19 |
| [프로그래머스] 가장 큰 수 찾기 (0) | 2025.11.13 |
| [프로그래머스] 택배 상자 꺼내기 (0) | 2025.11.11 |
| [프로그래머스] [PCCP 기출문제] 1번 / 동영상 재생기 (0) | 2025.11.10 |