Image
Kotlin/Collection

[Kotlin Collection] 3. Kotlin map, flatMap 을 이용해 데이터 변환하기

목차로 돌아가기

 

[Kotlin Collection] Kotlin에서 확장함수를 이용해 Collection 조작하기

목표 Collection 확장함수가 하는 일을 이해한다. 자유롭게 확장 함수를 이용해 데이터를 조작한다. 개요  Kotlin에서는 일반 컬렉션에도 함수형 프로그래밍을 위한 확장 함수를 제공하여, 데이터를

kotlinworld.com

 

목표

  • 변환함수의 개념을 익히고, map과 flatMap의 차이점을 익힌다.
  • map을 사용하는 방법을 익힌다.
  • flatMap을 사용하는 방법을 익힌다.

확장함수 목록

map

map는 Collection을 다른 형태로 변환해주기 위해 사용한다.

 

  • map : map은 인자로 받은 transform function을 통해 기존 Collection을 변형시킨 List를 return 한다.
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> 
(0..5).map { Pair(it, it) } // [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
(0..5).map { it * 3 } // [0, 3, 6, 9, 12, 15]

 

  • mapIndexed : mapIndex는 Iterable의 index 값을 가진 transform function을 통해 index를 포함한 List로 변형시킬 수 있도록 해준다.
public inline fun <T, R> Iterable<T>.mapIndexed(transform: (index: Int, T) -> R): List<R> {
('a'..'z').mapIndexed { index, i -> Pair(index, i) } // [(0, a), (1, b), (2, c), (3, d), (4, e), (5, f), (6, g), (7, h), (8, i), (9, j), (10, k), (11, l), (12, m), (13, n), (14, o), (15, p), (16, q), (17, r), (18, s), (19, t), (20, u), (21, v), (22, w), (23, x), (24, y), (25, z)]

 

  • mapTo : mapTo는 특정한 수신값(destination)에 transform시켜 넣어주는 연산이다.
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) -> R): C
val mutableList: MutableList<Char> = mutableListOf()
('a'..'z').toList().mapTo(mutableList) { it }
print(mutableList) // [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
val intList: MutableList<Int> = mutableListOf()
(1..10).mapTo(intList) { it * it } // 수신값을 intList로 지정
print(intList) // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

  • mapIndexedTo: mapTo에 index가 포함된 버전이다.
var intPairList: MutableList<Pair<Int, Int>> = mutableListOf()
(1..10).mapIndexedTo(intPairList) { index, it -> Pair(index, it * it) }
print(intPairList) // [(0, 1), (1, 4), (2, 9), (3, 16), (4, 25), (5, 36), (6, 49), (7, 64), (8, 81), (9, 100)]

 

 

flatMap

flatMap은 감싸져 있는 Collection을 하나로 합치기 위한 연산이다.

 

  • flatMap : Collection 내부에 Collection이 들어있는 경우, 내부의 Collection을 펼쳐주는 연산이다. 내부의 컬렉션 자체가 인자가 되는데, 이 때 인자에서 어떤 것만 take할 것인지를 한 연산으로 수행 가능하다.
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> 
val testList = listOf(listOf(1, 2), listOf(7, 8, 9), mutableListOf(4, 5, 6))
testList.flatMap { it : List<Int> -> it } // [1, 2, 7, 8, 9, 4, 5, 6]
testList.flatMap { it : List<Int> -> it.take(1) } // [1, 7, 4]

 

반응형

 

이 글의 저작권은 '조세영의 Kotlin World' 에 있습니다. 글, 이미지 무단 재배포 및 변경을 금지합니다.

 

 

Kotlin, Android, Spring 사용자 오픈 카톡

오셔서 궁금한 점을 질문해보세요!
비밀번호 : kotlin22

open.kakao.com