Constructing list from multi level map in Java 8












6















I have a multi-level map as follows:



 Map<String, Map<String, Student> outerMap = 
{"cls1" : {"xyz" : Student(rollNumber=1, name="test1")},
"cls2" : {"abc" : Student(rollNumber=2, name="test2")}}


Now I want to construct a list of string from the above map as follows:



["In class cls1 xyz with roll number 1",
"In class cls2 abc with roll number 2"]


I have written as follows, but this is not working, in this context I have gone through the post as well: Java 8 Streams - Nested Maps to List, but did not get much idea.



 List<String> classes = outerMap.keySet();
List<String> studentList = classes.stream()
.map(cls ->
outerMap.get(cls).keySet().stream()
.map(student -> "In class "+ cls +
student + " with roll number " +
outerMap.get(cls).get(student).getRollNum() +"n"
).collect(Collectors.toList());









share|improve this question



























    6















    I have a multi-level map as follows:



     Map<String, Map<String, Student> outerMap = 
    {"cls1" : {"xyz" : Student(rollNumber=1, name="test1")},
    "cls2" : {"abc" : Student(rollNumber=2, name="test2")}}


    Now I want to construct a list of string from the above map as follows:



    ["In class cls1 xyz with roll number 1",
    "In class cls2 abc with roll number 2"]


    I have written as follows, but this is not working, in this context I have gone through the post as well: Java 8 Streams - Nested Maps to List, but did not get much idea.



     List<String> classes = outerMap.keySet();
    List<String> studentList = classes.stream()
    .map(cls ->
    outerMap.get(cls).keySet().stream()
    .map(student -> "In class "+ cls +
    student + " with roll number " +
    outerMap.get(cls).get(student).getRollNum() +"n"
    ).collect(Collectors.toList());









    share|improve this question

























      6












      6








      6


      1






      I have a multi-level map as follows:



       Map<String, Map<String, Student> outerMap = 
      {"cls1" : {"xyz" : Student(rollNumber=1, name="test1")},
      "cls2" : {"abc" : Student(rollNumber=2, name="test2")}}


      Now I want to construct a list of string from the above map as follows:



      ["In class cls1 xyz with roll number 1",
      "In class cls2 abc with roll number 2"]


      I have written as follows, but this is not working, in this context I have gone through the post as well: Java 8 Streams - Nested Maps to List, but did not get much idea.



       List<String> classes = outerMap.keySet();
      List<String> studentList = classes.stream()
      .map(cls ->
      outerMap.get(cls).keySet().stream()
      .map(student -> "In class "+ cls +
      student + " with roll number " +
      outerMap.get(cls).get(student).getRollNum() +"n"
      ).collect(Collectors.toList());









      share|improve this question














      I have a multi-level map as follows:



       Map<String, Map<String, Student> outerMap = 
      {"cls1" : {"xyz" : Student(rollNumber=1, name="test1")},
      "cls2" : {"abc" : Student(rollNumber=2, name="test2")}}


      Now I want to construct a list of string from the above map as follows:



      ["In class cls1 xyz with roll number 1",
      "In class cls2 abc with roll number 2"]


      I have written as follows, but this is not working, in this context I have gone through the post as well: Java 8 Streams - Nested Maps to List, but did not get much idea.



       List<String> classes = outerMap.keySet();
      List<String> studentList = classes.stream()
      .map(cls ->
      outerMap.get(cls).keySet().stream()
      .map(student -> "In class "+ cls +
      student + " with roll number " +
      outerMap.get(cls).get(student).getRollNum() +"n"
      ).collect(Collectors.toList());






      java list java-8 hashmap






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 1 hour ago









      JoyJoy

      1,09472352




      1,09472352
























          3 Answers
          3






          active

          oldest

          votes


















          4














          You can simply use Map.forEach for this operation as:



          List<String> messages = new ArrayList<>();
          outerMap.forEach((cls, students) ->
          students.forEach((name, student) ->
          messages.add(convertToMessage(cls, name, student.getRollNumber()))));


          where convertToMessage is a util as :



          // this could be made cleaner using 'format'
          String convertToMessage(String cls, String studentName, String rollNumber) {
          return "In class" + cls + "--> " + studentName + " with roll number: " + rollNumber;
          }





          share|improve this answer

































            1














            One method use Java 8 Stream and lambda function:



            String format = "In class %s %s with roll number %d";
            List<String> result = new ArrayList<>();
            outerMap.entrySet().stream()
            .forEach(v -> {
            String className = v.getKey();
            v.getValue().entrySet().stream()
            .forEach(stringStudentEntry -> result.add(String.format(format,className,stringStudentEntry.getKey(),stringStudentEntry.getValue().getRollNumber())));
            });





            share|improve this answer































              1














              You may do it like so,



              List<String> formattedOutput = outerMap
              .entrySet().stream()
              .flatMap(e -> e.getValue().entrySet().stream().map(se -> "In class " + e.getKey()
              + " " + se.getKey() + " with roll number " + se.getValue().getRollNumber()))
              .collect(Collectors.toList());


              You have to use the flatMap operator instead of map operator.






              share|improve this answer





















              • 1





                @nullpointer Thanks for pointing that out. I have updated my answer.

                – Ravindra Ranwala
                33 mins 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%2f54229285%2fconstructing-list-from-multi-level-map-in-java-8%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









              4














              You can simply use Map.forEach for this operation as:



              List<String> messages = new ArrayList<>();
              outerMap.forEach((cls, students) ->
              students.forEach((name, student) ->
              messages.add(convertToMessage(cls, name, student.getRollNumber()))));


              where convertToMessage is a util as :



              // this could be made cleaner using 'format'
              String convertToMessage(String cls, String studentName, String rollNumber) {
              return "In class" + cls + "--> " + studentName + " with roll number: " + rollNumber;
              }





              share|improve this answer






























                4














                You can simply use Map.forEach for this operation as:



                List<String> messages = new ArrayList<>();
                outerMap.forEach((cls, students) ->
                students.forEach((name, student) ->
                messages.add(convertToMessage(cls, name, student.getRollNumber()))));


                where convertToMessage is a util as :



                // this could be made cleaner using 'format'
                String convertToMessage(String cls, String studentName, String rollNumber) {
                return "In class" + cls + "--> " + studentName + " with roll number: " + rollNumber;
                }





                share|improve this answer




























                  4












                  4








                  4







                  You can simply use Map.forEach for this operation as:



                  List<String> messages = new ArrayList<>();
                  outerMap.forEach((cls, students) ->
                  students.forEach((name, student) ->
                  messages.add(convertToMessage(cls, name, student.getRollNumber()))));


                  where convertToMessage is a util as :



                  // this could be made cleaner using 'format'
                  String convertToMessage(String cls, String studentName, String rollNumber) {
                  return "In class" + cls + "--> " + studentName + " with roll number: " + rollNumber;
                  }





                  share|improve this answer















                  You can simply use Map.forEach for this operation as:



                  List<String> messages = new ArrayList<>();
                  outerMap.forEach((cls, students) ->
                  students.forEach((name, student) ->
                  messages.add(convertToMessage(cls, name, student.getRollNumber()))));


                  where convertToMessage is a util as :



                  // this could be made cleaner using 'format'
                  String convertToMessage(String cls, String studentName, String rollNumber) {
                  return "In class" + cls + "--> " + studentName + " with roll number: " + rollNumber;
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 21 mins ago

























                  answered 1 hour ago









                  nullpointernullpointer

                  45.5k1096185




                  45.5k1096185

























                      1














                      One method use Java 8 Stream and lambda function:



                      String format = "In class %s %s with roll number %d";
                      List<String> result = new ArrayList<>();
                      outerMap.entrySet().stream()
                      .forEach(v -> {
                      String className = v.getKey();
                      v.getValue().entrySet().stream()
                      .forEach(stringStudentEntry -> result.add(String.format(format,className,stringStudentEntry.getKey(),stringStudentEntry.getValue().getRollNumber())));
                      });





                      share|improve this answer




























                        1














                        One method use Java 8 Stream and lambda function:



                        String format = "In class %s %s with roll number %d";
                        List<String> result = new ArrayList<>();
                        outerMap.entrySet().stream()
                        .forEach(v -> {
                        String className = v.getKey();
                        v.getValue().entrySet().stream()
                        .forEach(stringStudentEntry -> result.add(String.format(format,className,stringStudentEntry.getKey(),stringStudentEntry.getValue().getRollNumber())));
                        });





                        share|improve this answer


























                          1












                          1








                          1







                          One method use Java 8 Stream and lambda function:



                          String format = "In class %s %s with roll number %d";
                          List<String> result = new ArrayList<>();
                          outerMap.entrySet().stream()
                          .forEach(v -> {
                          String className = v.getKey();
                          v.getValue().entrySet().stream()
                          .forEach(stringStudentEntry -> result.add(String.format(format,className,stringStudentEntry.getKey(),stringStudentEntry.getValue().getRollNumber())));
                          });





                          share|improve this answer













                          One method use Java 8 Stream and lambda function:



                          String format = "In class %s %s with roll number %d";
                          List<String> result = new ArrayList<>();
                          outerMap.entrySet().stream()
                          .forEach(v -> {
                          String className = v.getKey();
                          v.getValue().entrySet().stream()
                          .forEach(stringStudentEntry -> result.add(String.format(format,className,stringStudentEntry.getKey(),stringStudentEntry.getValue().getRollNumber())));
                          });






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 34 mins ago









                          TongChenTongChen

                          21529




                          21529























                              1














                              You may do it like so,



                              List<String> formattedOutput = outerMap
                              .entrySet().stream()
                              .flatMap(e -> e.getValue().entrySet().stream().map(se -> "In class " + e.getKey()
                              + " " + se.getKey() + " with roll number " + se.getValue().getRollNumber()))
                              .collect(Collectors.toList());


                              You have to use the flatMap operator instead of map operator.






                              share|improve this answer





















                              • 1





                                @nullpointer Thanks for pointing that out. I have updated my answer.

                                – Ravindra Ranwala
                                33 mins ago
















                              1














                              You may do it like so,



                              List<String> formattedOutput = outerMap
                              .entrySet().stream()
                              .flatMap(e -> e.getValue().entrySet().stream().map(se -> "In class " + e.getKey()
                              + " " + se.getKey() + " with roll number " + se.getValue().getRollNumber()))
                              .collect(Collectors.toList());


                              You have to use the flatMap operator instead of map operator.






                              share|improve this answer





















                              • 1





                                @nullpointer Thanks for pointing that out. I have updated my answer.

                                – Ravindra Ranwala
                                33 mins ago














                              1












                              1








                              1







                              You may do it like so,



                              List<String> formattedOutput = outerMap
                              .entrySet().stream()
                              .flatMap(e -> e.getValue().entrySet().stream().map(se -> "In class " + e.getKey()
                              + " " + se.getKey() + " with roll number " + se.getValue().getRollNumber()))
                              .collect(Collectors.toList());


                              You have to use the flatMap operator instead of map operator.






                              share|improve this answer















                              You may do it like so,



                              List<String> formattedOutput = outerMap
                              .entrySet().stream()
                              .flatMap(e -> e.getValue().entrySet().stream().map(se -> "In class " + e.getKey()
                              + " " + se.getKey() + " with roll number " + se.getValue().getRollNumber()))
                              .collect(Collectors.toList());


                              You have to use the flatMap operator instead of map operator.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited 21 mins ago

























                              answered 52 mins ago









                              Ravindra RanwalaRavindra Ranwala

                              8,71531634




                              8,71531634








                              • 1





                                @nullpointer Thanks for pointing that out. I have updated my answer.

                                – Ravindra Ranwala
                                33 mins ago














                              • 1





                                @nullpointer Thanks for pointing that out. I have updated my answer.

                                – Ravindra Ranwala
                                33 mins ago








                              1




                              1





                              @nullpointer Thanks for pointing that out. I have updated my answer.

                              – Ravindra Ranwala
                              33 mins ago





                              @nullpointer Thanks for pointing that out. I have updated my answer.

                              – Ravindra Ranwala
                              33 mins 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.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54229285%2fconstructing-list-from-multi-level-map-in-java-8%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 other Star Trek series did the main TNG cast show up in?

                              Berlina muro

                              Berlina aerponto