Java streams map class property list to flattened mapJava 8 Nested (Multi level) group byHow do I efficiently iterate over each entry in a Java Map?Java inner class and static nested classMost efficient way to increment a Map value in JavaEfficiency of Java “Double Brace Initialization”?How to convert a Map to List in Java?Static Classes In JavaRetrieving a List from a java.util.stream.Stream in Java 8Ways to iterate over a list in JavaJava 8 List<V> into Map<K, V>How to Convert a Java 8 Stream to an Array?

Should I be able to keep my company purchased standing desk when I leave my job?

Pi 3 B+ no audio device found

Vienna To Graz By Rail

What is the meaning of [[:space:]] in bash?

Is there a typesafe way to get a Database.QueryLocator?

Why did Steve Rogers choose this character in Endgame?

Sending a photo of my bank account card to the future employer

Does this sentence I constructed with my junior high school latin work? I write online advertising and want to come off as snobby as possible

Why doesn't philosophy have higher standards for its arguments?

How can electric field be defined as force per charge, if the charge makes its own, singular electric field?

What is the difference between a Hosaka, Ono-Sendai, and a "deck"?

Is the purpose of sheet music to be played along to? Or a guide for learning and reference during playing?

A verb to describe specific positioning of three layers

Strategy to pay off revolving debt while building reserve savings fund?

Why is Google approaching my VPS machine?

Why is Katakana not pronounced Katagana?

Can a Resident Assistant be told to ignore a lawful order?'

How can a drink contain 1.8 kcal energy while 0 g fat/carbs/protein?

At which point can a system be compromised when downloading archived data from an untrusted source?

How possible is a successful landing just with 1 wing?

Is it rude to refer to janitors as 'floor people'?

Credit card details stolen every 1-2 years. What am I doing wrong?

How fast does a character need to move to be effectively invisible?

What is the point of a constraint expression on a non-templated function?



Java streams map class property list to flattened map


Java 8 Nested (Multi level) group byHow do I efficiently iterate over each entry in a Java Map?Java inner class and static nested classMost efficient way to increment a Map value in JavaEfficiency of Java “Double Brace Initialization”?How to convert a Map to List in Java?Static Classes In JavaRetrieving a List from a java.util.stream.Stream in Java 8Ways to iterate over a list in JavaJava 8 List<V> into Map<K, V>How to Convert a Java 8 Stream to an Array?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















How can we turn a List<Foo> towards a Map<propertyA, List<propertyB>> in the most optimal way by using java streams.



Beware: propertyA is NOT unique



//pseudo-code
class Foo
propertyA //not unique
List<propertyB>


So far I have the following:



fooList.stream()
.collect(Collectors.groupingBy(Foo::propertyA,
Collectors.mapping(Foo::propertyB, Collectors.toList())))


Resulting into a Map<propretyA, List<List<propretyB>>> which is not yet flattened for its value.










share|improve this question






























    3















    How can we turn a List<Foo> towards a Map<propertyA, List<propertyB>> in the most optimal way by using java streams.



    Beware: propertyA is NOT unique



    //pseudo-code
    class Foo
    propertyA //not unique
    List<propertyB>


    So far I have the following:



    fooList.stream()
    .collect(Collectors.groupingBy(Foo::propertyA,
    Collectors.mapping(Foo::propertyB, Collectors.toList())))


    Resulting into a Map<propretyA, List<List<propretyB>>> which is not yet flattened for its value.










    share|improve this question


























      3












      3








      3








      How can we turn a List<Foo> towards a Map<propertyA, List<propertyB>> in the most optimal way by using java streams.



      Beware: propertyA is NOT unique



      //pseudo-code
      class Foo
      propertyA //not unique
      List<propertyB>


      So far I have the following:



      fooList.stream()
      .collect(Collectors.groupingBy(Foo::propertyA,
      Collectors.mapping(Foo::propertyB, Collectors.toList())))


      Resulting into a Map<propretyA, List<List<propretyB>>> which is not yet flattened for its value.










      share|improve this question
















      How can we turn a List<Foo> towards a Map<propertyA, List<propertyB>> in the most optimal way by using java streams.



      Beware: propertyA is NOT unique



      //pseudo-code
      class Foo
      propertyA //not unique
      List<propertyB>


      So far I have the following:



      fooList.stream()
      .collect(Collectors.groupingBy(Foo::propertyA,
      Collectors.mapping(Foo::propertyB, Collectors.toList())))


      Resulting into a Map<propretyA, List<List<propretyB>>> which is not yet flattened for its value.







      java java-stream






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 13 at 19:44









      Ruslan

      5,0411 gold badge13 silver badges31 bronze badges




      5,0411 gold badge13 silver badges31 bronze badges










      asked Mar 13 at 19:28









      TerenceTerence

      7,7611 gold badge10 silver badges19 bronze badges




      7,7611 gold badge10 silver badges19 bronze badges






















          3 Answers
          3






          active

          oldest

          votes


















          5














          You could use Java 9+ Collectors.flatMapping:



          Map<propretyA, List<propretyB>> result = fooList.stream()
          .collect(Collectors.groupingBy(Foo::propertyA,
          Collectors.flatMapping(foo -> foo.propertyB().stream(),
          Collectors.toList())));


          Another way (Java8+) is by using Collectors.toMap as in this answer.



          And yet another Java8+ way is to just not use streams, but use Map.computeIfAbsent instead:



          Map<propretyA, List<propretyB>> result = new LinkedHashMap<>();
          fooList.forEach(foo -> result.computeIfAbsent(foo.propertyA(), k -> new ArrayList<>())
          .addAll(foo.propertyB()));





          share|improve this answer




















          • 3





            …and if Java 9 is not an option, a backport of flatMapping is at the end of this answer

            – Holger
            Mar 13 at 22:19


















          4














          This should do it:



           fooList.stream()
          .collect(Collectors.toMap(Foo::getPropertyA, Foo::getPropertyBList, (l1, l2) ->
          l1.addAll(l2);
          return l1;
          ));





          share|improve this answer






























            1














            You could use Collectors.toMap with merge function where you have to decide which List<propertyB> has to be used when duplicating keys:



            Map<propertyA, List<propertyB>> collect = list.stream()
            .collect(Collectors.toMap(Foo::getPropertyA, Foo::getList, (l1, l2) -> ???));


            Otherwise you can get IllegalStateException. From javadoc:




            If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.




            It is up to you how to implement merge function, but usually you just want to return the union of 2 lists like: l1.addAll(l2); return l1;






            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',
              autoActivateHeartbeat: false,
              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%2f55149854%2fjava-streams-map-class-property-list-to-flattened-map%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              5














              You could use Java 9+ Collectors.flatMapping:



              Map<propretyA, List<propretyB>> result = fooList.stream()
              .collect(Collectors.groupingBy(Foo::propertyA,
              Collectors.flatMapping(foo -> foo.propertyB().stream(),
              Collectors.toList())));


              Another way (Java8+) is by using Collectors.toMap as in this answer.



              And yet another Java8+ way is to just not use streams, but use Map.computeIfAbsent instead:



              Map<propretyA, List<propretyB>> result = new LinkedHashMap<>();
              fooList.forEach(foo -> result.computeIfAbsent(foo.propertyA(), k -> new ArrayList<>())
              .addAll(foo.propertyB()));





              share|improve this answer




















              • 3





                …and if Java 9 is not an option, a backport of flatMapping is at the end of this answer

                – Holger
                Mar 13 at 22:19















              5














              You could use Java 9+ Collectors.flatMapping:



              Map<propretyA, List<propretyB>> result = fooList.stream()
              .collect(Collectors.groupingBy(Foo::propertyA,
              Collectors.flatMapping(foo -> foo.propertyB().stream(),
              Collectors.toList())));


              Another way (Java8+) is by using Collectors.toMap as in this answer.



              And yet another Java8+ way is to just not use streams, but use Map.computeIfAbsent instead:



              Map<propretyA, List<propretyB>> result = new LinkedHashMap<>();
              fooList.forEach(foo -> result.computeIfAbsent(foo.propertyA(), k -> new ArrayList<>())
              .addAll(foo.propertyB()));





              share|improve this answer




















              • 3





                …and if Java 9 is not an option, a backport of flatMapping is at the end of this answer

                – Holger
                Mar 13 at 22:19













              5












              5








              5







              You could use Java 9+ Collectors.flatMapping:



              Map<propretyA, List<propretyB>> result = fooList.stream()
              .collect(Collectors.groupingBy(Foo::propertyA,
              Collectors.flatMapping(foo -> foo.propertyB().stream(),
              Collectors.toList())));


              Another way (Java8+) is by using Collectors.toMap as in this answer.



              And yet another Java8+ way is to just not use streams, but use Map.computeIfAbsent instead:



              Map<propretyA, List<propretyB>> result = new LinkedHashMap<>();
              fooList.forEach(foo -> result.computeIfAbsent(foo.propertyA(), k -> new ArrayList<>())
              .addAll(foo.propertyB()));





              share|improve this answer















              You could use Java 9+ Collectors.flatMapping:



              Map<propretyA, List<propretyB>> result = fooList.stream()
              .collect(Collectors.groupingBy(Foo::propertyA,
              Collectors.flatMapping(foo -> foo.propertyB().stream(),
              Collectors.toList())));


              Another way (Java8+) is by using Collectors.toMap as in this answer.



              And yet another Java8+ way is to just not use streams, but use Map.computeIfAbsent instead:



              Map<propretyA, List<propretyB>> result = new LinkedHashMap<>();
              fooList.forEach(foo -> result.computeIfAbsent(foo.propertyA(), k -> new ArrayList<>())
              .addAll(foo.propertyB()));






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 13 at 20:35

























              answered Mar 13 at 20:28









              Federico Peralta SchaffnerFederico Peralta Schaffner

              24.5k5 gold badges38 silver badges83 bronze badges




              24.5k5 gold badges38 silver badges83 bronze badges







              • 3





                …and if Java 9 is not an option, a backport of flatMapping is at the end of this answer

                – Holger
                Mar 13 at 22:19












              • 3





                …and if Java 9 is not an option, a backport of flatMapping is at the end of this answer

                – Holger
                Mar 13 at 22:19







              3




              3





              …and if Java 9 is not an option, a backport of flatMapping is at the end of this answer

              – Holger
              Mar 13 at 22:19





              …and if Java 9 is not an option, a backport of flatMapping is at the end of this answer

              – Holger
              Mar 13 at 22:19













              4














              This should do it:



               fooList.stream()
              .collect(Collectors.toMap(Foo::getPropertyA, Foo::getPropertyBList, (l1, l2) ->
              l1.addAll(l2);
              return l1;
              ));





              share|improve this answer



























                4














                This should do it:



                 fooList.stream()
                .collect(Collectors.toMap(Foo::getPropertyA, Foo::getPropertyBList, (l1, l2) ->
                l1.addAll(l2);
                return l1;
                ));





                share|improve this answer

























                  4












                  4








                  4







                  This should do it:



                   fooList.stream()
                  .collect(Collectors.toMap(Foo::getPropertyA, Foo::getPropertyBList, (l1, l2) ->
                  l1.addAll(l2);
                  return l1;
                  ));





                  share|improve this answer













                  This should do it:



                   fooList.stream()
                  .collect(Collectors.toMap(Foo::getPropertyA, Foo::getPropertyBList, (l1, l2) ->
                  l1.addAll(l2);
                  return l1;
                  ));






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 13 at 20:07









                  Not a JDNot a JD

                  1,4021 silver badge12 bronze badges




                  1,4021 silver badge12 bronze badges





















                      1














                      You could use Collectors.toMap with merge function where you have to decide which List<propertyB> has to be used when duplicating keys:



                      Map<propertyA, List<propertyB>> collect = list.stream()
                      .collect(Collectors.toMap(Foo::getPropertyA, Foo::getList, (l1, l2) -> ???));


                      Otherwise you can get IllegalStateException. From javadoc:




                      If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.




                      It is up to you how to implement merge function, but usually you just want to return the union of 2 lists like: l1.addAll(l2); return l1;






                      share|improve this answer





























                        1














                        You could use Collectors.toMap with merge function where you have to decide which List<propertyB> has to be used when duplicating keys:



                        Map<propertyA, List<propertyB>> collect = list.stream()
                        .collect(Collectors.toMap(Foo::getPropertyA, Foo::getList, (l1, l2) -> ???));


                        Otherwise you can get IllegalStateException. From javadoc:




                        If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.




                        It is up to you how to implement merge function, but usually you just want to return the union of 2 lists like: l1.addAll(l2); return l1;






                        share|improve this answer



























                          1












                          1








                          1







                          You could use Collectors.toMap with merge function where you have to decide which List<propertyB> has to be used when duplicating keys:



                          Map<propertyA, List<propertyB>> collect = list.stream()
                          .collect(Collectors.toMap(Foo::getPropertyA, Foo::getList, (l1, l2) -> ???));


                          Otherwise you can get IllegalStateException. From javadoc:




                          If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.




                          It is up to you how to implement merge function, but usually you just want to return the union of 2 lists like: l1.addAll(l2); return l1;






                          share|improve this answer















                          You could use Collectors.toMap with merge function where you have to decide which List<propertyB> has to be used when duplicating keys:



                          Map<propertyA, List<propertyB>> collect = list.stream()
                          .collect(Collectors.toMap(Foo::getPropertyA, Foo::getList, (l1, l2) -> ???));


                          Otherwise you can get IllegalStateException. From javadoc:




                          If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.




                          It is up to you how to implement merge function, but usually you just want to return the union of 2 lists like: l1.addAll(l2); return l1;







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 26 at 9:14

























                          answered Mar 13 at 19:36









                          RuslanRuslan

                          5,0411 gold badge13 silver badges31 bronze badges




                          5,0411 gold badge13 silver badges31 bronze badges



























                              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.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55149854%2fjava-streams-map-class-property-list-to-flattened-map%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

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript