What is the use case for flatMap vs map in kotlin

前端 未结 2 1895
予麋鹿
予麋鹿 2021-02-05 02:26

in https://try.kotlinlang.org/#/Kotlin%20Koans/Collections/FlatMap/Task.kt

it has sample of using flatMap and map

seems both are doing

2条回答
  •  心在旅途
    2021-02-05 03:11

    Consider the following example: You have a simple data structure Data with a single property of type List.

    class Data(val items : List)
    
    val dataObjects = listOf(
        Data(listOf("a", "b", "c")), 
        Data(listOf("1", "2", "3"))
    )
    

    flatMap vs. map

    With flatMap, you can "flatten" multiple Data::items into one collection as shown with the items variable.

    val items: List = dataObjects
        .flatMap { it.items } //[a, b, c, 1, 2, 3]
    

    Using map, on the other hand, simply results in a list of lists.

    val items2: List> = dataObjects
        .map { it.items } //[[a, b, c], [1, 2, 3]] 
    

    flatten

    There's also a flatten extension on Iterable> and also Array> which you can use alternatively to flatMap when using those types:

    val nestedCollections: List = 
        listOf(listOf(1,2,3), listOf(5,4,3))
            .flatten() //[1, 2, 3, 5, 4, 3]
    

提交回复
热议问题