티스토리 뷰

kotlin

map vs flatMap

길 킴 2020. 9. 7. 17:48
728x90

볼 때 마다 헷갈리는 map과 flatMap을 파헤쳐 보겠다. 

// map 예제
val data = listOf("A", "B", "C")
val newData = data.map { "$it*" }
println("data: $newData")

// flatMap 예제
val data2 = listOf("A", "B", "C")
val newData2 = data.flatMap { listOf("$it*") }
println("data2: $newData2")

---출력 결과---
data: [A*, B*, C*]
data2: [A*, B*, C*]

 

Collections 클래스에서 map과 flatMap 함수를 살펴보자 

1. map 함수 

/**
 * Returns a list containing the results of applying the given [transform] function
 * to each element in the original collection.
 * 
 * @sample samples.collections.Collections.Transformations.map
 */
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
    return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}


/**
 * Applies the given [transform] function to each element of the original collection
 * and appends the results to the given [destination].
 */
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) -> R): C {
    for (item in this)
        destination.add(transform(item))
    return destination
}

=> 변형(transform)한 후, 하나한 씩 add() 한다. 

2. flatMap

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
 * 
 * @sample samples.collections.Collections.Transformations.flatMap
 */
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

/**
 * Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination].
 */
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) -> Iterable<R>): C {
    for (element in this) {
        val list = transform(element)
        destination.addAll(list)
    }
    return destination
}

=> 변형하고 리스트를 만든다. 그리고 addAll() 한다. 

 

 


flatMap을 언제 사용하면 유용할까? 

val data2 = listOf("A", "B", "C")
val newData2 = data.flatMap { listOf("$it", "seperator") }
println("data2: $newData2")

---출력 결과---
data2: [A, seperator, B, seperator, C, seperator]

위에 처럼 List의 각 데이터를 가공하여 증가 시킬 때 사용하면 유용할 것 같다. 
(자주 사용하진 않아서, 실 업무에서는 언제 사용하면 도움이 될 지 아시는 분은 적어주시면 감사하겠습니다~)

'kotlin' 카테고리의 다른 글

Reified란? (Type Eraser)  (0) 2020.09.07
Kotlin - filter, map 은 알겠는데, Sqeuence 란?  (0) 2020.05.25
SAM Conversions  (0) 2019.12.30
Generic  (0) 2019.10.15
Kotlin - Nested / Inner class  (0) 2019.08.25
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함