Constructing list from multi level map in Java 8












11















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



























    11















    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

























      11












      11








      11


      3






      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 Jan 17 at 4:58









      JoyJoy

      1,12172353




      1,12172353
























          3 Answers
          3






          active

          oldest

          votes


















          11














          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

































            5














            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

































              2














              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























                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









                11














                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






























                  11














                  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




























                    11












                    11








                    11







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

























                    answered Jan 17 at 5:04









                    nullpointernullpointer

                    46.2k1198188




                    46.2k1198188

























                        5














                        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






























                          5














                          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




























                            5












                            5








                            5







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

























                            answered Jan 17 at 5:16









                            Ravindra RanwalaRavindra Ranwala

                            8,85531634




                            8,85531634























                                2














                                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




























                                  2














                                  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


























                                    2












                                    2








                                    2







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









                                    TongChenTongChen

                                    31529




                                    31529






























                                        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

                                        1300-talet

                                        1300-talet

                                        Display a custom attribute below product name in the front-end Magento 1.9.3.8