5.2 컬렉션 함수형 API - ericbykim/kotlin-in-action GitHub Wiki
- 5.2.1 filter, map, maxBy, mapKeys, mapValues, filterKeys, filterValues
- 5.2.2 all, any, count, find, firstOrNull
- 5.2.3 groupBy
5.2.1 filter, map, maxBy, mapKeys, mapValues, filterKeys, filterValues
filter
listOfNums.filter { it % 2 == 0 } // 짝수만
people.filter { it.age > 30 } // 30살 초과하는 사람
map
listOfNums.map { it * it } // 제곱
people.map { it.name } // 이름 리스트
people.map(Person::name)
maxBy
// 가장 나이가 많은 사람 리스트 (효율적이지 않은 방법)
people.filter { it.age == people.maxBy(Person::age)!!.age } // 나이 최댓값을 매번 계산
// 가장 나이가 많은 사람 리스트 (더 효율적인 방법)
val maxAge = people.maxBy(Person::age)!!.age // 나이 최댓값을 한번 계산
people.filter { it.age == maxAge }
mapValues
val numbers = mapOf(0 to "zero", 1 to "one")
numbers.mapValues { it.value.toUpperCase() } // 결과: {0=ZERO, 1=ONE}
그 외: mapKeys, filterKeys, filterValues
5.2.2 all, any, count, find, firstOrNull
all
,any
로 조건을 만족하는지 판단count
조건을 만족하는 원소 개수find
조건을 만족하는 첫 번째 원소를 반환
val under27 = { p: Person -> p.age <= 27 } // 27살 이하인지 판단
people.all(under27) // 모두 27살 이하?
people.any(under27) // 한 명이라도 27살 이하?
people.count(under27) // 27살 이하 몇명?
people.find(under27) // 27살 이하인 원소 하나 반환, 없으면 null 반환
people.firstOrNull(under27) // find와 같다. null이 반환될 수 있다는 사실이 더 명확하다.
De Morgan's Theorem:
!all(긍정조건)
는 any(부정조건)
과 같고, !any(긍정조건)
는 all(부정조건)
과 같다.
!list.all{ it == 3 }
list.any { it != 3 } // 같은 결과
5.2.3 groupBy
원소를 분류할 때 유용
val people.groupBy { it.age } // 나이별로 분류