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












20















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





























    20















    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



























      20












      20








      20


      4






      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 Jan 6 at 4:36









      Nicholas K

      6,59261132




      6,59261132










      asked Jan 5 at 17:31









      Yassine Ben HamidaYassine Ben Hamida

      370113




      370113
























          6 Answers
          6






          active

          oldest

          votes


















          29














          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































            11














            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





















            • 1





              @Aomine values() may involve a construction of an expensive intermediate object, thus simply ignoring k may be advantageous from a performance perspective.

              – oakad
              Jan 6 at 7:01











            • @oakad You're correct in the sense that values may involve creating a new object but note that the returned collection by values is lazily created once, thereafter, the same instance will be returned. So it's not so expensive after all. Further, I'd favour readability here which means map.values().forEach(list::addAll).

              – Aomine
              Jan 6 at 10:13





















            9














            Here's an alternate way to do it with Java-9 and above:



            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
              Jan 5 at 17:46








            • 9





              It decreases indeed the readability here. The Java 8 way is clearly more relevant here.

              – davidxxx
              Jan 5 at 17:52



















            5














            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














              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

























                  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









                  29














                  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




























                    29














                    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


























                      29












                      29








                      29







                      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 Jan 5 at 17:32









                      AomineAomine

                      41.9k74071




                      41.9k74071

























                          11














                          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





















                          • 1





                            @Aomine values() may involve a construction of an expensive intermediate object, thus simply ignoring k may be advantageous from a performance perspective.

                            – oakad
                            Jan 6 at 7:01











                          • @oakad You're correct in the sense that values may involve creating a new object but note that the returned collection by values is lazily created once, thereafter, the same instance will be returned. So it's not so expensive after all. Further, I'd favour readability here which means map.values().forEach(list::addAll).

                            – Aomine
                            Jan 6 at 10:13


















                          11














                          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





















                          • 1





                            @Aomine values() may involve a construction of an expensive intermediate object, thus simply ignoring k may be advantageous from a performance perspective.

                            – oakad
                            Jan 6 at 7:01











                          • @oakad You're correct in the sense that values may involve creating a new object but note that the returned collection by values is lazily created once, thereafter, the same instance will be returned. So it's not so expensive after all. Further, I'd favour readability here which means map.values().forEach(list::addAll).

                            – Aomine
                            Jan 6 at 10:13
















                          11












                          11








                          11







                          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 Jan 5 at 17:42

























                          answered Jan 5 at 17:39









                          Hadi JHadi J

                          10.2k31744




                          10.2k31744








                          • 1





                            @Aomine values() may involve a construction of an expensive intermediate object, thus simply ignoring k may be advantageous from a performance perspective.

                            – oakad
                            Jan 6 at 7:01











                          • @oakad You're correct in the sense that values may involve creating a new object but note that the returned collection by values is lazily created once, thereafter, the same instance will be returned. So it's not so expensive after all. Further, I'd favour readability here which means map.values().forEach(list::addAll).

                            – Aomine
                            Jan 6 at 10:13
















                          • 1





                            @Aomine values() may involve a construction of an expensive intermediate object, thus simply ignoring k may be advantageous from a performance perspective.

                            – oakad
                            Jan 6 at 7:01











                          • @oakad You're correct in the sense that values may involve creating a new object but note that the returned collection by values is lazily created once, thereafter, the same instance will be returned. So it's not so expensive after all. Further, I'd favour readability here which means map.values().forEach(list::addAll).

                            – Aomine
                            Jan 6 at 10:13










                          1




                          1





                          @Aomine values() may involve a construction of an expensive intermediate object, thus simply ignoring k may be advantageous from a performance perspective.

                          – oakad
                          Jan 6 at 7:01





                          @Aomine values() may involve a construction of an expensive intermediate object, thus simply ignoring k may be advantageous from a performance perspective.

                          – oakad
                          Jan 6 at 7:01













                          @oakad You're correct in the sense that values may involve creating a new object but note that the returned collection by values is lazily created once, thereafter, the same instance will be returned. So it's not so expensive after all. Further, I'd favour readability here which means map.values().forEach(list::addAll).

                          – Aomine
                          Jan 6 at 10:13







                          @oakad You're correct in the sense that values may involve creating a new object but note that the returned collection by values is lazily created once, thereafter, the same instance will be returned. So it's not so expensive after all. Further, I'd favour readability here which means map.values().forEach(list::addAll).

                          – Aomine
                          Jan 6 at 10:13













                          9














                          Here's an alternate way to do it with Java-9 and above:



                          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
                            Jan 5 at 17:46








                          • 9





                            It decreases indeed the readability here. The Java 8 way is clearly more relevant here.

                            – davidxxx
                            Jan 5 at 17:52
















                          9














                          Here's an alternate way to do it with Java-9 and above:



                          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
                            Jan 5 at 17:46








                          • 9





                            It decreases indeed the readability here. The Java 8 way is clearly more relevant here.

                            – davidxxx
                            Jan 5 at 17:52














                          9












                          9








                          9







                          Here's an alternate way to do it with Java-9 and above:



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





                          share|improve this answer















                          Here's an alternate way to do it with Java-9 and above:



                          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








                          edited Jan 6 at 5:44









                          nullpointer

                          46.5k1199190




                          46.5k1199190










                          answered Jan 5 at 17:33









                          Ravindra RanwalaRavindra Ranwala

                          9,06031634




                          9,06031634








                          • 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
                            Jan 5 at 17:46








                          • 9





                            It decreases indeed the readability here. The Java 8 way is clearly more relevant here.

                            – davidxxx
                            Jan 5 at 17:52














                          • 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
                            Jan 5 at 17:46








                          • 9





                            It decreases indeed the readability here. The Java 8 way is clearly more relevant here.

                            – davidxxx
                            Jan 5 at 17:52








                          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
                          Jan 5 at 17:46







                          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
                          Jan 5 at 17:46






                          9




                          9





                          It decreases indeed the readability here. The Java 8 way is clearly more relevant here.

                          – davidxxx
                          Jan 5 at 17:52





                          It decreases indeed the readability here. The Java 8 way is clearly more relevant here.

                          – davidxxx
                          Jan 5 at 17:52











                          5














                          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




























                            5














                            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


























                              5












                              5








                              5







                              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 Jan 5 at 17:40









                              ETOETO

                              2,663526




                              2,663526























                                  4














                                  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






























                                    4














                                    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




























                                      4












                                      4








                                      4







                                      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 Jan 6 at 4:39

























                                      answered Jan 5 at 17:38









                                      nullpointernullpointer

                                      46.5k1199190




                                      46.5k1199190























                                          2














                                          Simply use :-



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





                                          share|improve this answer






























                                            2














                                            Simply use :-



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





                                            share|improve this answer




























                                              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 Jan 6 at 4:37

























                                              answered Jan 5 at 17:34









                                              Nicholas KNicholas K

                                              6,59261132




                                              6,59261132






























                                                  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%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

                                                  MongoDB - Not Authorized To Execute Command

                                                  How to fix TextFormField cause rebuild widget in Flutter

                                                  Npm cannot find a required file even through it is in the searched directory