How to get a List from a HashMap<String,List>












6














I want to extract a List<E> from a Map<String,List<E>> (E is a random Class) using stream().



I want a simple one-line method using java 8's stream.



What I have tried until now :



HashMap<String,List<E>> map = new HashMap<>();
List<E> list = map.values(); // does not compile
list = map.values().stream().collect(Collectors.toList()); // does not compile









share|improve this question





























    6














    I want to extract a List<E> from a Map<String,List<E>> (E is a random Class) using stream().



    I want a simple one-line method using java 8's stream.



    What I have tried until now :



    HashMap<String,List<E>> map = new HashMap<>();
    List<E> list = map.values(); // does not compile
    list = map.values().stream().collect(Collectors.toList()); // does not compile









    share|improve this question



























      6












      6








      6


      3





      I want to extract a List<E> from a Map<String,List<E>> (E is a random Class) using stream().



      I want a simple one-line method using java 8's stream.



      What I have tried until now :



      HashMap<String,List<E>> map = new HashMap<>();
      List<E> list = map.values(); // does not compile
      list = map.values().stream().collect(Collectors.toList()); // does not compile









      share|improve this question















      I want to extract a List<E> from a Map<String,List<E>> (E is a random Class) using stream().



      I want a simple one-line method using java 8's stream.



      What I have tried until now :



      HashMap<String,List<E>> map = new HashMap<>();
      List<E> list = map.values(); // does not compile
      list = map.values().stream().collect(Collectors.toList()); // does not compile






      java collections java-8 java-stream collectors






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 18 mins ago









      Nicholas K

      5,81951031




      5,81951031










      asked 11 hours ago









      Yassine Ben Hamida

      13111




      13111
























          6 Answers
          6






          active

          oldest

          votes


















          7














          map.values() returns a Collection<List<E>> not a List<E>, if you want the latter then you're required to flatten the nested List<E> into a single List<E> as follows:



          List<E> result = map.values()
          .stream()
          .flatMap(List::stream)
          .collect(Collectors.toList());





          share|improve this answer





























            5














            Here's the Java9 solution,



            List<E> result = map.values().stream()
            .collect(Collectors.flatMapping(List::stream, Collectors.toList()));





            share|improve this answer

















            • 6




              Just the apiNote :- The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy.
              – nullpointer
              11 hours ago








            • 3




              It decreases indeed the readability here. The Java 8 way is clearly more relevant here.
              – davidxxx
              11 hours ago






            • 2




              In fact it is not the Java 9 solution. It is a way possible with Java 9. But the Java 9 way to favor is of course the same as with Java 8 : stackoverflow.com/a/54054456/270371
              – davidxxx
              10 hours ago





















            4














            In addition to other answers:



            List<E> result = map.values()
            .stream()
            .collect(ArrayList::new, List::addAll, List::addAll);


            This could also do the trick.






            share|improve this answer





























              3














              Or use forEach



               map.forEach((k,v)->list.addAll(v));


              or as Aomine commented use this



              map.values().forEach(list::addAll);





              share|improve this answer



















              • 3




                good idea in showing a non-stream version. btw it would be better to iterate over the values since you're not doing anything with the k i.e. you can do List<String> result = new ArrayList<>(); map.values().forEach(result::addAll);
                – Aomine
                11 hours ago



















              3














              You can use Collection.stream with flatMap as:



              Map<String, List<E>> map = new HashMap<>(); // program to interface
              List<E> list = map.values()
              .stream()
              .flatMap(Collection::stream)
              .collect(Collectors.toList());


              or use a non-stream version as:



              List<E> list = new ArrayList<>();
              map.values().forEach(list::addAll)





              share|improve this answer































                2














                Simply use :-



                map.values().stream().flatMap(List::stream).collect(Collectors.toList());





                share|improve this answer



















                • 1




                  This wont' work, rather it will give you List<List<E>>
                  – Ravindra Ranwala
                  11 hours ago













                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%2f54054448%2fhow-to-get-a-liste-from-a-hashmapstring-liste%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                6 Answers
                6






                active

                oldest

                votes








                6 Answers
                6






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                7














                map.values() returns a Collection<List<E>> not a List<E>, if you want the latter then you're required to flatten the nested List<E> into a single List<E> as follows:



                List<E> result = map.values()
                .stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());





                share|improve this answer


























                  7














                  map.values() returns a Collection<List<E>> not a List<E>, if you want the latter then you're required to flatten the nested List<E> into a single List<E> as follows:



                  List<E> result = map.values()
                  .stream()
                  .flatMap(List::stream)
                  .collect(Collectors.toList());





                  share|improve this answer
























                    7












                    7








                    7






                    map.values() returns a Collection<List<E>> not a List<E>, if you want the latter then you're required to flatten the nested List<E> into a single List<E> as follows:



                    List<E> result = map.values()
                    .stream()
                    .flatMap(List::stream)
                    .collect(Collectors.toList());





                    share|improve this answer












                    map.values() returns a Collection<List<E>> not a List<E>, if you want the latter then you're required to flatten the nested List<E> into a single List<E> as follows:



                    List<E> result = map.values()
                    .stream()
                    .flatMap(List::stream)
                    .collect(Collectors.toList());






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 11 hours ago









                    Aomine

                    40.7k73870




                    40.7k73870

























                        5














                        Here's the Java9 solution,



                        List<E> result = map.values().stream()
                        .collect(Collectors.flatMapping(List::stream, Collectors.toList()));





                        share|improve this answer

















                        • 6




                          Just the apiNote :- The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy.
                          – nullpointer
                          11 hours ago








                        • 3




                          It decreases indeed the readability here. The Java 8 way is clearly more relevant here.
                          – davidxxx
                          11 hours ago






                        • 2




                          In fact it is not the Java 9 solution. It is a way possible with Java 9. But the Java 9 way to favor is of course the same as with Java 8 : stackoverflow.com/a/54054456/270371
                          – davidxxx
                          10 hours ago


















                        5














                        Here's the Java9 solution,



                        List<E> result = map.values().stream()
                        .collect(Collectors.flatMapping(List::stream, Collectors.toList()));





                        share|improve this answer

















                        • 6




                          Just the apiNote :- The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy.
                          – nullpointer
                          11 hours ago








                        • 3




                          It decreases indeed the readability here. The Java 8 way is clearly more relevant here.
                          – davidxxx
                          11 hours ago






                        • 2




                          In fact it is not the Java 9 solution. It is a way possible with Java 9. But the Java 9 way to favor is of course the same as with Java 8 : stackoverflow.com/a/54054456/270371
                          – davidxxx
                          10 hours ago
















                        5












                        5








                        5






                        Here's the Java9 solution,



                        List<E> result = map.values().stream()
                        .collect(Collectors.flatMapping(List::stream, Collectors.toList()));





                        share|improve this answer












                        Here's the Java9 solution,



                        List<E> result = map.values().stream()
                        .collect(Collectors.flatMapping(List::stream, Collectors.toList()));






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered 11 hours ago









                        Ravindra Ranwala

                        8,52231634




                        8,52231634








                        • 6




                          Just the apiNote :- The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy.
                          – nullpointer
                          11 hours ago








                        • 3




                          It decreases indeed the readability here. The Java 8 way is clearly more relevant here.
                          – davidxxx
                          11 hours ago






                        • 2




                          In fact it is not the Java 9 solution. It is a way possible with Java 9. But the Java 9 way to favor is of course the same as with Java 8 : stackoverflow.com/a/54054456/270371
                          – davidxxx
                          10 hours ago
















                        • 6




                          Just the apiNote :- The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy.
                          – nullpointer
                          11 hours ago








                        • 3




                          It decreases indeed the readability here. The Java 8 way is clearly more relevant here.
                          – davidxxx
                          11 hours ago






                        • 2




                          In fact it is not the Java 9 solution. It is a way possible with Java 9. But the Java 9 way to favor is of course the same as with Java 8 : stackoverflow.com/a/54054456/270371
                          – davidxxx
                          10 hours ago










                        6




                        6




                        Just the apiNote :- The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy.
                        – nullpointer
                        11 hours ago






                        Just the apiNote :- The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy.
                        – nullpointer
                        11 hours ago






                        3




                        3




                        It decreases indeed the readability here. The Java 8 way is clearly more relevant here.
                        – davidxxx
                        11 hours ago




                        It decreases indeed the readability here. The Java 8 way is clearly more relevant here.
                        – davidxxx
                        11 hours ago




                        2




                        2




                        In fact it is not the Java 9 solution. It is a way possible with Java 9. But the Java 9 way to favor is of course the same as with Java 8 : stackoverflow.com/a/54054456/270371
                        – davidxxx
                        10 hours ago






                        In fact it is not the Java 9 solution. It is a way possible with Java 9. But the Java 9 way to favor is of course the same as with Java 8 : stackoverflow.com/a/54054456/270371
                        – davidxxx
                        10 hours ago













                        4














                        In addition to other answers:



                        List<E> result = map.values()
                        .stream()
                        .collect(ArrayList::new, List::addAll, List::addAll);


                        This could also do the trick.






                        share|improve this answer


























                          4














                          In addition to other answers:



                          List<E> result = map.values()
                          .stream()
                          .collect(ArrayList::new, List::addAll, List::addAll);


                          This could also do the trick.






                          share|improve this answer
























                            4












                            4








                            4






                            In addition to other answers:



                            List<E> result = map.values()
                            .stream()
                            .collect(ArrayList::new, List::addAll, List::addAll);


                            This could also do the trick.






                            share|improve this answer












                            In addition to other answers:



                            List<E> result = map.values()
                            .stream()
                            .collect(ArrayList::new, List::addAll, List::addAll);


                            This could also do the trick.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 11 hours ago









                            ETO

                            1,886422




                            1,886422























                                3














                                Or use forEach



                                 map.forEach((k,v)->list.addAll(v));


                                or as Aomine commented use this



                                map.values().forEach(list::addAll);





                                share|improve this answer



















                                • 3




                                  good idea in showing a non-stream version. btw it would be better to iterate over the values since you're not doing anything with the k i.e. you can do List<String> result = new ArrayList<>(); map.values().forEach(result::addAll);
                                  – Aomine
                                  11 hours ago
















                                3














                                Or use forEach



                                 map.forEach((k,v)->list.addAll(v));


                                or as Aomine commented use this



                                map.values().forEach(list::addAll);





                                share|improve this answer



















                                • 3




                                  good idea in showing a non-stream version. btw it would be better to iterate over the values since you're not doing anything with the k i.e. you can do List<String> result = new ArrayList<>(); map.values().forEach(result::addAll);
                                  – Aomine
                                  11 hours ago














                                3












                                3








                                3






                                Or use forEach



                                 map.forEach((k,v)->list.addAll(v));


                                or as Aomine commented use this



                                map.values().forEach(list::addAll);





                                share|improve this answer














                                Or use forEach



                                 map.forEach((k,v)->list.addAll(v));


                                or as Aomine commented use this



                                map.values().forEach(list::addAll);






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited 11 hours ago

























                                answered 11 hours ago









                                Hadi J

                                9,86231742




                                9,86231742








                                • 3




                                  good idea in showing a non-stream version. btw it would be better to iterate over the values since you're not doing anything with the k i.e. you can do List<String> result = new ArrayList<>(); map.values().forEach(result::addAll);
                                  – Aomine
                                  11 hours ago














                                • 3




                                  good idea in showing a non-stream version. btw it would be better to iterate over the values since you're not doing anything with the k i.e. you can do List<String> result = new ArrayList<>(); map.values().forEach(result::addAll);
                                  – Aomine
                                  11 hours ago








                                3




                                3




                                good idea in showing a non-stream version. btw it would be better to iterate over the values since you're not doing anything with the k i.e. you can do List<String> result = new ArrayList<>(); map.values().forEach(result::addAll);
                                – Aomine
                                11 hours ago




                                good idea in showing a non-stream version. btw it would be better to iterate over the values since you're not doing anything with the k i.e. you can do List<String> result = new ArrayList<>(); map.values().forEach(result::addAll);
                                – Aomine
                                11 hours ago











                                3














                                You can use Collection.stream with flatMap as:



                                Map<String, List<E>> map = new HashMap<>(); // program to interface
                                List<E> list = map.values()
                                .stream()
                                .flatMap(Collection::stream)
                                .collect(Collectors.toList());


                                or use a non-stream version as:



                                List<E> list = new ArrayList<>();
                                map.values().forEach(list::addAll)





                                share|improve this answer




























                                  3














                                  You can use Collection.stream with flatMap as:



                                  Map<String, List<E>> map = new HashMap<>(); // program to interface
                                  List<E> list = map.values()
                                  .stream()
                                  .flatMap(Collection::stream)
                                  .collect(Collectors.toList());


                                  or use a non-stream version as:



                                  List<E> list = new ArrayList<>();
                                  map.values().forEach(list::addAll)





                                  share|improve this answer


























                                    3












                                    3








                                    3






                                    You can use Collection.stream with flatMap as:



                                    Map<String, List<E>> map = new HashMap<>(); // program to interface
                                    List<E> list = map.values()
                                    .stream()
                                    .flatMap(Collection::stream)
                                    .collect(Collectors.toList());


                                    or use a non-stream version as:



                                    List<E> list = new ArrayList<>();
                                    map.values().forEach(list::addAll)





                                    share|improve this answer














                                    You can use Collection.stream with flatMap as:



                                    Map<String, List<E>> map = new HashMap<>(); // program to interface
                                    List<E> list = map.values()
                                    .stream()
                                    .flatMap(Collection::stream)
                                    .collect(Collectors.toList());


                                    or use a non-stream version as:



                                    List<E> list = new ArrayList<>();
                                    map.values().forEach(list::addAll)






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited 15 mins ago

























                                    answered 11 hours ago









                                    nullpointer

                                    43.4k1093178




                                    43.4k1093178























                                        2














                                        Simply use :-



                                        map.values().stream().flatMap(List::stream).collect(Collectors.toList());





                                        share|improve this answer



















                                        • 1




                                          This wont' work, rather it will give you List<List<E>>
                                          – Ravindra Ranwala
                                          11 hours ago


















                                        2














                                        Simply use :-



                                        map.values().stream().flatMap(List::stream).collect(Collectors.toList());





                                        share|improve this answer



















                                        • 1




                                          This wont' work, rather it will give you List<List<E>>
                                          – Ravindra Ranwala
                                          11 hours ago
















                                        2












                                        2








                                        2






                                        Simply use :-



                                        map.values().stream().flatMap(List::stream).collect(Collectors.toList());





                                        share|improve this answer














                                        Simply use :-



                                        map.values().stream().flatMap(List::stream).collect(Collectors.toList());






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited 17 mins ago

























                                        answered 11 hours ago









                                        Nicholas K

                                        5,81951031




                                        5,81951031








                                        • 1




                                          This wont' work, rather it will give you List<List<E>>
                                          – Ravindra Ranwala
                                          11 hours ago
















                                        • 1




                                          This wont' work, rather it will give you List<List<E>>
                                          – Ravindra Ranwala
                                          11 hours ago










                                        1




                                        1




                                        This wont' work, rather it will give you List<List<E>>
                                        – Ravindra Ranwala
                                        11 hours ago






                                        This wont' work, rather it will give you List<List<E>>
                                        – Ravindra Ranwala
                                        11 hours ago




















                                        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%2f54054448%2fhow-to-get-a-liste-from-a-hashmapstring-liste%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

                                        What visual should I use to simply compare current year value vs last year in Power BI desktop

                                        How to ignore python UserWarning in pytest?

                                        Alexandru Averescu