[Kotlin] associateBy

Yuri Lee·2022년 7월 29일
0

Intro

진행하는 프로젝트의 백엔드 코드가 Kotlin 로 이루어져 있어서 Kotlin 문법을 익히고 있다. 이번 시간에는 코틀린의 associateBy 에 대해 알아보도록 하자.

associateBy

inline fun <T, K> Sequence<T>.associateBy(
    keySelector: (T) -> K
): Map<K, T>
(source)

Returns a Map containing the elements from the given sequence indexed by the key returned from keySelector function applied to each element.
If any two elements would have the same key returned by keySelector the last one gets added to the map.

각 요소에 적용된 keySelector 함수에서 반환된 키로 인덱싱된 지정된 시퀀스의 요소를 포함하는 맵을 반환한다. 두 요소가 keySelector에 의해 동일한 키를 반환하면 마지막 요소가 맵에 추가된다. 반환된 맵은 원래 시퀀스의 항목 반복 순서를 유지한다.

Example

 */
fun main() {
    val charCodes = intArrayOf(72, 69, 76, 76, 79)
    val byChar = charCodes.associateBy { it.toChar() }
    println(byChar) // {H=72, E=69, L=76, O=79}
}

key는 중복이 허용되지 않지만, 값은 중복이 허용되고 이미 저장되어 있는 키로 값을 저장 시 기존 저장되어 있던 값은 사라지고 새로운 값으로 대체된다.


https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/associate-by.html
https://mond-al.github.io/kotlin-associateBy-groupBy-partition

profile
Step by step goes a long way ✨

0개의 댓글