What is the use case for flatMap vs map in kotlin

前端 未结 2 1893
予麋鹿
予麋鹿 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 02:59

    There are three functions in play here. map(), flatten(), and flatMap() which is a combination of the first two.

    Consider the following example

    data class Hero (val name:String)
    data class Universe (val heroes: List)
    
    val batman = Hero("Bruce Wayne")
    val wonderWoman = Hero (name = "Diana Prince")
    
    val mailMan = Hero("Stan Lee")
    val deadPool = Hero("Wade Winston Wilson")
    
    val marvel = Universe(listOf(mailMan, deadPool))
    val dc = Universe(listOf(batman, wonderWoman))
    
    val allHeroes: List = listOf(marvel, dc)
    

    Map

    allHeroes.map { it.heroes }
    
    // output: [[Hero(name=Stan Lee), Hero(name=Wade Winston Wilson)], [Hero(name=Bruce Wayne), Hero(name=Diana Prince)]]
    

    Map allows you to access each universe in {allHeroes} and (in this case) return its list of heroes. So the output will be a list containing two lists of heroes, one for each universe. The result is a List>

    Flatmap

    allHeroes.flatMap { it.heroes } 
    
    // output: [Hero(name=Stan Lee), Hero(name=Wade Winston Wilson), Hero(name=Bruce Wayne), Hero(name=Diana Prince)]
    

    FlatMap allows you to do the same as map, access the two lists of heroes from both universes. But it goes further and flattens the returned list of lists into a single list. The result is a List

    Flatten

    allHeroes.map { it.heroes }.flatten() 
    
    // output: [Hero(name=Stan Lee), Hero(name=Wade Winston Wilson), Hero(name=Bruce Wayne), Hero(name=Diana Prince)]
    

    This produces the same result as flatMap. So flatMap is a combination of the two functions, map{} and then flatten()

提交回复
热议问题