Kotlin 코딩테스트 문법 시리즈 ⑩ : 고차 함수 정리 (map, filter, any 등)

2025. 7. 10. 03:41·Code Odyssey

✅ Kotlin은 고차 함수(Higher-Order Functions)를 이용해 컬렉션 데이터를 매우 간결하게 다룰 수 있습니다.


🔹 map

✅ 각 요소 변환

val nums = listOf(1, 2, 3)
val doubled = nums.map { it * 2 }  // [2, 4, 6]
  • 요소를 변환해 새로운 리스트 반환
  • 원본은 변경되지 않음

🔹 mapIndexed

✅ 인덱스를 활용해 요소 변환 후 새 리스트로 생성

val names = listOf("Tom", "Jane", "Mike")
val indexed = names.mapIndexed { index, name -> "$index:$name" }  // ["0:Tom", "1:Jane", "2:Mike"]
val evenIndex = items.mapIndexedNotNull { index, name -> if (index % 2 == 0) "$index:$name" else null } // ["0:Tom", "2:Mike"]
  • 각 요소의 인덱스와 값을 함께 활용해 변환 가능
  • map과 달리 인덱스 정보를 함께 사용할 수 있음
  • 순번 포함 출력, 좌표 계산 등에 자주 활용

🔹 filter

✅ 조건에 맞는 요소만 필터링

val nums = listOf(1, 2, 3, 4, 5)
val even = nums.filter { it % 2 == 0 }  // [2, 4]

🔹 any / all / none

✅ 일부/모두/전혀 만족 여부 확인

val nums = listOf(1, 2, 3)

nums.any { it > 2 }    // true (하나라도 만족)
nums.all { it > 0 }    // true (모두 만족)
nums.none { it < 0 }   // true (모두 불만족)

🔹 count

✅ 조건을 만족하는 개수

val nums = listOf(1, 2, 3, 4)
val cnt = nums.count { it % 2 == 0 }  // 2

🔹 find / firstOrNull

✅ 조건을 만족하는 첫 번째 요소 찾기

val nums = listOf(1, 2, 3)
val firstOver1 = nums.find { it > 1 }  // 2
val noneFound = nums.find { it > 10 }  // null

🔹 groupBy

✅ 특정 기준으로 그룹화

val words = listOf("apple", "ant", "banana", "bear")
val grouped = words.groupBy { it.first() }
// 결과: {a=[apple, ant], b=[banana, bear]}

🔹 distinct / distinctBy

✅ 중복 제거

val nums = listOf(1, 2, 2, 3)
val distinct = nums.distinct()  // [1, 2, 3]

val people = listOf("Kim", "Lee", "Park", "Lee")
val unique = people.distinct()  // [Kim, Lee, Park]
// 예: 이름 앞글자 기준 중복 제거
val names = listOf("Alex", "Alice", "Bob", "Brian")
val result = names.distinctBy { it.first() }  // [Alex, Bob]

🔹 기타 유용한 함수

✅ take / takeWhile / drop / dropWhile

val list = listOf(1, 2, 3, 4, 5)

list.take(3)               // [1, 2, 3]
list.takeWhile { it < 4 }  // [1, 2, 3]

list.drop(2)               // [3, 4, 5]
list.dropWhile { it < 3 }  // [3, 4, 5]

🔹 filter와 takeWhile의 차이:

  • filter: 전체 순회하며 조건을 만족하는 요소 필터링
  • takeWhile: 앞에서부터 조건 만족하는 동안만 유지 → 중간에서 조건 불만족되면 거기서 멈춤
val list = listOf(1, 2, 3, 1, 2)
list.filter { it < 3 }       // [1, 2, 1, 2]
list.takeWhile { it < 3 }    // [1, 2]  ← 3에서 중단

✅ partition — 조건 기준으로 두 그룹 분리

val (even, odd) = listOf(1, 2, 3, 4).partition { it % 2 == 0 }
// even: [2, 4], odd: [1, 3]

✅ 체이닝 예시

val result = listOf(5, 3, 1, 4, 2)
    .filter { it % 2 == 1 }      // 홀수만 → [5, 3, 1]
    .map { it * it }             // 제곱 → [25, 9, 1]
    .sortedDescending()          // 내림차순 정렬 → [25, 9, 1]
  • map, filter, sorted 등은 연속으로 체이닝 가능
  • 불변 리스트로 이어지며 코드 가독성/간결성 향상

✅ 요약 정리

함수 설명
map 요소 변환 (새 리스트 반환)
mapIndexed 인덱스 활용 요소 변환 (새 리스트 반환)
filter 조건 만족 요소 필터링
any / all / none 조건 만족 여부 검사
count 조건 만족 요소 수 계산
find / firstOrNull 조건에 맞는 첫 요소 반환 (or null)
groupBy 기준별 그룹핑 (Map 반환)
distinct / distinctBy 중복 제거

다음은 시리즈 ⑪: 컬렉션 유틸 함수 정리 (zip, chunked, windowed 등) 으로 이어집니다.

'Code Odyssey' 카테고리의 다른 글

Kotlin 코딩테스트 문법 시리즈 ⑫ : 누적 함수 정리 (reduce, fold, scan)  (1) 2025.07.12
Kotlin 코딩테스트 문법 시리즈 ⑪ : 컬렉션 유틸 함수 정리 (zip, chunked, windowed 등)  (4) 2025.07.11
Kotlin 코딩테스트 문법 시리즈 ⑨ : 정렬 (기본, 조건, 다중 기준)  (1) 2025.07.09
Kotlin 코딩테스트 문법 시리즈 ⑧ : 스택 / 큐 / 우선순위 큐 정리  (0) 2025.07.08
Kotlin 코딩테스트 문법 시리즈 ⑦ : 2차원 배열(리스트) 정리  (2) 2025.07.07
'Code Odyssey' 카테고리의 다른 글
  • Kotlin 코딩테스트 문법 시리즈 ⑫ : 누적 함수 정리 (reduce, fold, scan)
  • Kotlin 코딩테스트 문법 시리즈 ⑪ : 컬렉션 유틸 함수 정리 (zip, chunked, windowed 등)
  • Kotlin 코딩테스트 문법 시리즈 ⑨ : 정렬 (기본, 조건, 다중 기준)
  • Kotlin 코딩테스트 문법 시리즈 ⑧ : 스택 / 큐 / 우선순위 큐 정리
Celion
Celion
오늘도 평소처럼 화이팅!
  • Celion
    Orion Log
    Celion
  • 전체
    오늘
    어제
    • 전체 글 (144)
      • Uncompiled Thoughts (8)
        • 네이버 부스트캠프 10기 (5)
      • CS 기초부터 한 걸음씩 (34)
      • Code Odyssey (22)
      • Algorithm (77)
        • Coding Test Records (63)
      • Git (3)
      • reference (0)
  • 블로그 메뉴

    • 태그
    • 방명록
  • 태그

    java
    greedy
    시뮬레이션
    코테
    알고리즘고득점kit
    Level3
    Level2
    boostcamp
    Kotlin
    문법정리
    프로그래머스
    백준
  • 최근 글

  • 인기 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.4
Celion
Kotlin 코딩테스트 문법 시리즈 ⑩ : 고차 함수 정리 (map, filter, any 등)
상단으로

티스토리툴바