What is the use case for flatMap vs map in kotlin











up vote
3
down vote

favorite












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



it has sample of using flatMap and map



seems both are doing the same thing, is there a sample to show the difference of using flatMap and map?



the data type:



data class Shop(val name: String, val customers: List<Customer>)

data class Customer(val name: String, val city: City, val orders: List<Order>) {
override fun toString() = "$name from ${city.name}"
}

data class Order(val products: List<Product>, val isDelivered: Boolean)

data class Product(val name: String, val price: Double) {
override fun toString() = "'$name' for $price"
}

data class City(val name: String) {
override fun toString() = name
}


the samples:



fun Shop.getCitiesCustomersAreFrom(): Set<City> =
customers.map { it.city }.toSet()
// would it be same with customers.flatMap { it.city }.toSet() ?

val Customer.orderedProducts: Set<Product> get() {
return orders.flatMap { it.products }.toSet()
// would it be same with return orders.map { it.products }.toSet()
}









share|improve this question




























    up vote
    3
    down vote

    favorite












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



    it has sample of using flatMap and map



    seems both are doing the same thing, is there a sample to show the difference of using flatMap and map?



    the data type:



    data class Shop(val name: String, val customers: List<Customer>)

    data class Customer(val name: String, val city: City, val orders: List<Order>) {
    override fun toString() = "$name from ${city.name}"
    }

    data class Order(val products: List<Product>, val isDelivered: Boolean)

    data class Product(val name: String, val price: Double) {
    override fun toString() = "'$name' for $price"
    }

    data class City(val name: String) {
    override fun toString() = name
    }


    the samples:



    fun Shop.getCitiesCustomersAreFrom(): Set<City> =
    customers.map { it.city }.toSet()
    // would it be same with customers.flatMap { it.city }.toSet() ?

    val Customer.orderedProducts: Set<Product> get() {
    return orders.flatMap { it.products }.toSet()
    // would it be same with return orders.map { it.products }.toSet()
    }









    share|improve this question


























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











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



      it has sample of using flatMap and map



      seems both are doing the same thing, is there a sample to show the difference of using flatMap and map?



      the data type:



      data class Shop(val name: String, val customers: List<Customer>)

      data class Customer(val name: String, val city: City, val orders: List<Order>) {
      override fun toString() = "$name from ${city.name}"
      }

      data class Order(val products: List<Product>, val isDelivered: Boolean)

      data class Product(val name: String, val price: Double) {
      override fun toString() = "'$name' for $price"
      }

      data class City(val name: String) {
      override fun toString() = name
      }


      the samples:



      fun Shop.getCitiesCustomersAreFrom(): Set<City> =
      customers.map { it.city }.toSet()
      // would it be same with customers.flatMap { it.city }.toSet() ?

      val Customer.orderedProducts: Set<Product> get() {
      return orders.flatMap { it.products }.toSet()
      // would it be same with return orders.map { it.products }.toSet()
      }









      share|improve this question















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



      it has sample of using flatMap and map



      seems both are doing the same thing, is there a sample to show the difference of using flatMap and map?



      the data type:



      data class Shop(val name: String, val customers: List<Customer>)

      data class Customer(val name: String, val city: City, val orders: List<Order>) {
      override fun toString() = "$name from ${city.name}"
      }

      data class Order(val products: List<Product>, val isDelivered: Boolean)

      data class Product(val name: String, val price: Double) {
      override fun toString() = "'$name' for $price"
      }

      data class City(val name: String) {
      override fun toString() = name
      }


      the samples:



      fun Shop.getCitiesCustomersAreFrom(): Set<City> =
      customers.map { it.city }.toSet()
      // would it be same with customers.flatMap { it.city }.toSet() ?

      val Customer.orderedProducts: Set<Product> get() {
      return orders.flatMap { it.products }.toSet()
      // would it be same with return orders.map { it.products }.toSet()
      }






      collections kotlin flatmap






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 29 at 13:24









      s1m0nw1

      24.7k63899




      24.7k63899










      asked Aug 29 at 13:06









      lannyf

      1,77311842




      1,77311842
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          7
          down vote



          accepted










          Have a look at this simple example:



          class Data(val items : List<String>)

          fun main(args: Array<String>) {
          val data = listOf(Data(listOf("a", "b", "c")), Data(listOf("1", "2", "3")))
          val items: List<String> = data.flatMap { it.items } //[a, b, c, 1, 2, 3]
          val items2: List<List<String>> = data.map { it.items } //[[a, b, c], [1, 2, 3]]
          }


          With flatMap, you can merge multiple collections into one as shown with the items variable. Using map, on the other hand, simply results in a list of lists.



          Note that there's a flatten extension on Iterable<Iterable<T>> and also Array<Array<T>> which you can use alternatively to flatMap:



          val nestedCollections: List<Int> = listOf(listOf(1,2,3), listOf(5,4,3)).flatten()





          share|improve this answer






























            up vote
            2
            down vote













            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<Hero>)

            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<Universe> = listOf(marvel, dc)

            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<List<Hero>>
            */

            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<Hero>
            */

            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()
            */





            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52078207%2fwhat-is-the-use-case-for-flatmap-vs-map-in-kotlin%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              7
              down vote



              accepted










              Have a look at this simple example:



              class Data(val items : List<String>)

              fun main(args: Array<String>) {
              val data = listOf(Data(listOf("a", "b", "c")), Data(listOf("1", "2", "3")))
              val items: List<String> = data.flatMap { it.items } //[a, b, c, 1, 2, 3]
              val items2: List<List<String>> = data.map { it.items } //[[a, b, c], [1, 2, 3]]
              }


              With flatMap, you can merge multiple collections into one as shown with the items variable. Using map, on the other hand, simply results in a list of lists.



              Note that there's a flatten extension on Iterable<Iterable<T>> and also Array<Array<T>> which you can use alternatively to flatMap:



              val nestedCollections: List<Int> = listOf(listOf(1,2,3), listOf(5,4,3)).flatten()





              share|improve this answer



























                up vote
                7
                down vote



                accepted










                Have a look at this simple example:



                class Data(val items : List<String>)

                fun main(args: Array<String>) {
                val data = listOf(Data(listOf("a", "b", "c")), Data(listOf("1", "2", "3")))
                val items: List<String> = data.flatMap { it.items } //[a, b, c, 1, 2, 3]
                val items2: List<List<String>> = data.map { it.items } //[[a, b, c], [1, 2, 3]]
                }


                With flatMap, you can merge multiple collections into one as shown with the items variable. Using map, on the other hand, simply results in a list of lists.



                Note that there's a flatten extension on Iterable<Iterable<T>> and also Array<Array<T>> which you can use alternatively to flatMap:



                val nestedCollections: List<Int> = listOf(listOf(1,2,3), listOf(5,4,3)).flatten()





                share|improve this answer

























                  up vote
                  7
                  down vote



                  accepted







                  up vote
                  7
                  down vote



                  accepted






                  Have a look at this simple example:



                  class Data(val items : List<String>)

                  fun main(args: Array<String>) {
                  val data = listOf(Data(listOf("a", "b", "c")), Data(listOf("1", "2", "3")))
                  val items: List<String> = data.flatMap { it.items } //[a, b, c, 1, 2, 3]
                  val items2: List<List<String>> = data.map { it.items } //[[a, b, c], [1, 2, 3]]
                  }


                  With flatMap, you can merge multiple collections into one as shown with the items variable. Using map, on the other hand, simply results in a list of lists.



                  Note that there's a flatten extension on Iterable<Iterable<T>> and also Array<Array<T>> which you can use alternatively to flatMap:



                  val nestedCollections: List<Int> = listOf(listOf(1,2,3), listOf(5,4,3)).flatten()





                  share|improve this answer














                  Have a look at this simple example:



                  class Data(val items : List<String>)

                  fun main(args: Array<String>) {
                  val data = listOf(Data(listOf("a", "b", "c")), Data(listOf("1", "2", "3")))
                  val items: List<String> = data.flatMap { it.items } //[a, b, c, 1, 2, 3]
                  val items2: List<List<String>> = data.map { it.items } //[[a, b, c], [1, 2, 3]]
                  }


                  With flatMap, you can merge multiple collections into one as shown with the items variable. Using map, on the other hand, simply results in a list of lists.



                  Note that there's a flatten extension on Iterable<Iterable<T>> and also Array<Array<T>> which you can use alternatively to flatMap:



                  val nestedCollections: List<Int> = listOf(listOf(1,2,3), listOf(5,4,3)).flatten()






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 21 at 19:46

























                  answered Aug 29 at 13:20









                  s1m0nw1

                  24.7k63899




                  24.7k63899
























                      up vote
                      2
                      down vote













                      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<Hero>)

                      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<Universe> = listOf(marvel, dc)

                      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<List<Hero>>
                      */

                      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<Hero>
                      */

                      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()
                      */





                      share|improve this answer



























                        up vote
                        2
                        down vote













                        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<Hero>)

                        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<Universe> = listOf(marvel, dc)

                        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<List<Hero>>
                        */

                        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<Hero>
                        */

                        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()
                        */





                        share|improve this answer

























                          up vote
                          2
                          down vote










                          up vote
                          2
                          down vote









                          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<Hero>)

                          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<Universe> = listOf(marvel, dc)

                          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<List<Hero>>
                          */

                          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<Hero>
                          */

                          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()
                          */





                          share|improve this answer














                          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<Hero>)

                          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<Universe> = listOf(marvel, dc)

                          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<List<Hero>>
                          */

                          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<Hero>
                          */

                          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()
                          */






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 19 at 23:38

























                          answered Nov 19 at 23:20









                          Dawit Abraham

                          316




                          316






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52078207%2fwhat-is-the-use-case-for-flatmap-vs-map-in-kotlin%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Berounka

                              Sphinx de Gizeh

                              Different font size/position of beamer's navigation symbols template's content depending on regular/plain...