Convert Map to Map<String, Set> with filter and streams












6














I would like to convert my map which looks like this:



{
key="someKey1", value=Apple(id="1", color="green"),
key="someKey2", value=Apple(id="2", color="red"),
key="someKey3", value=Apple(id="3", color="green"),
key="someKey4", value=Apple(id="4", color="red"),
}


to another map which puts all apples of the same color into the same list:



{
key="red", value=list={apple1, apple3},
key="green", value=list={apple2, apple4},
}


I tried the following:



Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
.stream()
.collect(Collectors.toMap(l -> l.getColour, ???));


Am I on the right track? Should I use filters for this task? Is there an easier way?










share|improve this question





























    6














    I would like to convert my map which looks like this:



    {
    key="someKey1", value=Apple(id="1", color="green"),
    key="someKey2", value=Apple(id="2", color="red"),
    key="someKey3", value=Apple(id="3", color="green"),
    key="someKey4", value=Apple(id="4", color="red"),
    }


    to another map which puts all apples of the same color into the same list:



    {
    key="red", value=list={apple1, apple3},
    key="green", value=list={apple2, apple4},
    }


    I tried the following:



    Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
    .stream()
    .collect(Collectors.toMap(l -> l.getColour, ???));


    Am I on the right track? Should I use filters for this task? Is there an easier way?










    share|improve this question



























      6












      6








      6







      I would like to convert my map which looks like this:



      {
      key="someKey1", value=Apple(id="1", color="green"),
      key="someKey2", value=Apple(id="2", color="red"),
      key="someKey3", value=Apple(id="3", color="green"),
      key="someKey4", value=Apple(id="4", color="red"),
      }


      to another map which puts all apples of the same color into the same list:



      {
      key="red", value=list={apple1, apple3},
      key="green", value=list={apple2, apple4},
      }


      I tried the following:



      Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
      .stream()
      .collect(Collectors.toMap(l -> l.getColour, ???));


      Am I on the right track? Should I use filters for this task? Is there an easier way?










      share|improve this question















      I would like to convert my map which looks like this:



      {
      key="someKey1", value=Apple(id="1", color="green"),
      key="someKey2", value=Apple(id="2", color="red"),
      key="someKey3", value=Apple(id="3", color="green"),
      key="someKey4", value=Apple(id="4", color="red"),
      }


      to another map which puts all apples of the same color into the same list:



      {
      key="red", value=list={apple1, apple3},
      key="green", value=list={apple2, apple4},
      }


      I tried the following:



      Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
      .stream()
      .collect(Collectors.toMap(l -> l.getColour, ???));


      Am I on the right track? Should I use filters for this task? Is there an easier way?







      java lambda java-8 java-stream






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 10 mins ago









      Aomine

      39.8k73770




      39.8k73770










      asked 34 mins ago









      M4V3N

      528




      528
























          3 Answers
          3






          active

          oldest

          votes


















          4














          Collectors.groupingBy is more suitable than Collectors.toMap for this task (though both can be used).



          Map<String, List<Apple>> sortedApples = 
          appleMap.values()
          .stream()
          .collect(Collectors.groupingBy(Apple::getColour));


          Or, to group them into Sets use:



          Map<String, Set<Apple>> sortedApples = 
          appleMap.values()
          .stream()
          .collect(Collectors.groupingBy(Apple::getColour,
          Collectors.mapping(Function.identity(),
          Collectors.toSet())));





          share|improve this answer





























            4














            You can use Collectors.groupingBy and Collectors.toSet()



            Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
            .stream() // Stream<Apple>
            .collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
            Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set





            share|improve this answer































              1














              if you want to proceed with toMap you can get the result as follows:



              map.entrySet()
              .stream()
              .collect(toMap(s -> s.getValue().getColour(),
              v -> new HashSet<>(singleton(v.getValue())),
              (l, r) -> {l.addAll(r); return l;}));


              But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.



              This is a job for the groupingBy collector shown in the other answers or do it shorter without a stream:



              Map<String, Set<Apple>> res = new HashMap<>();
              map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));





              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%2f54005438%2fconvert-mapstring-object-to-mapstring-setobject-with-filter-and-streams%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














                Collectors.groupingBy is more suitable than Collectors.toMap for this task (though both can be used).



                Map<String, List<Apple>> sortedApples = 
                appleMap.values()
                .stream()
                .collect(Collectors.groupingBy(Apple::getColour));


                Or, to group them into Sets use:



                Map<String, Set<Apple>> sortedApples = 
                appleMap.values()
                .stream()
                .collect(Collectors.groupingBy(Apple::getColour,
                Collectors.mapping(Function.identity(),
                Collectors.toSet())));





                share|improve this answer


























                  4














                  Collectors.groupingBy is more suitable than Collectors.toMap for this task (though both can be used).



                  Map<String, List<Apple>> sortedApples = 
                  appleMap.values()
                  .stream()
                  .collect(Collectors.groupingBy(Apple::getColour));


                  Or, to group them into Sets use:



                  Map<String, Set<Apple>> sortedApples = 
                  appleMap.values()
                  .stream()
                  .collect(Collectors.groupingBy(Apple::getColour,
                  Collectors.mapping(Function.identity(),
                  Collectors.toSet())));





                  share|improve this answer
























                    4












                    4








                    4






                    Collectors.groupingBy is more suitable than Collectors.toMap for this task (though both can be used).



                    Map<String, List<Apple>> sortedApples = 
                    appleMap.values()
                    .stream()
                    .collect(Collectors.groupingBy(Apple::getColour));


                    Or, to group them into Sets use:



                    Map<String, Set<Apple>> sortedApples = 
                    appleMap.values()
                    .stream()
                    .collect(Collectors.groupingBy(Apple::getColour,
                    Collectors.mapping(Function.identity(),
                    Collectors.toSet())));





                    share|improve this answer












                    Collectors.groupingBy is more suitable than Collectors.toMap for this task (though both can be used).



                    Map<String, List<Apple>> sortedApples = 
                    appleMap.values()
                    .stream()
                    .collect(Collectors.groupingBy(Apple::getColour));


                    Or, to group them into Sets use:



                    Map<String, Set<Apple>> sortedApples = 
                    appleMap.values()
                    .stream()
                    .collect(Collectors.groupingBy(Apple::getColour,
                    Collectors.mapping(Function.identity(),
                    Collectors.toSet())));






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 31 mins ago









                    Eran

                    279k37452537




                    279k37452537

























                        4














                        You can use Collectors.groupingBy and Collectors.toSet()



                        Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
                        .stream() // Stream<Apple>
                        .collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
                        Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set





                        share|improve this answer




























                          4














                          You can use Collectors.groupingBy and Collectors.toSet()



                          Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
                          .stream() // Stream<Apple>
                          .collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
                          Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set





                          share|improve this answer


























                            4












                            4








                            4






                            You can use Collectors.groupingBy and Collectors.toSet()



                            Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
                            .stream() // Stream<Apple>
                            .collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
                            Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set





                            share|improve this answer














                            You can use Collectors.groupingBy and Collectors.toSet()



                            Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
                            .stream() // Stream<Apple>
                            .collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
                            Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 16 mins ago

























                            answered 30 mins ago









                            nullpointer

                            42.5k1090175




                            42.5k1090175























                                1














                                if you want to proceed with toMap you can get the result as follows:



                                map.entrySet()
                                .stream()
                                .collect(toMap(s -> s.getValue().getColour(),
                                v -> new HashSet<>(singleton(v.getValue())),
                                (l, r) -> {l.addAll(r); return l;}));


                                But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.



                                This is a job for the groupingBy collector shown in the other answers or do it shorter without a stream:



                                Map<String, Set<Apple>> res = new HashMap<>();
                                map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));





                                share|improve this answer




























                                  1














                                  if you want to proceed with toMap you can get the result as follows:



                                  map.entrySet()
                                  .stream()
                                  .collect(toMap(s -> s.getValue().getColour(),
                                  v -> new HashSet<>(singleton(v.getValue())),
                                  (l, r) -> {l.addAll(r); return l;}));


                                  But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.



                                  This is a job for the groupingBy collector shown in the other answers or do it shorter without a stream:



                                  Map<String, Set<Apple>> res = new HashMap<>();
                                  map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));





                                  share|improve this answer


























                                    1












                                    1








                                    1






                                    if you want to proceed with toMap you can get the result as follows:



                                    map.entrySet()
                                    .stream()
                                    .collect(toMap(s -> s.getValue().getColour(),
                                    v -> new HashSet<>(singleton(v.getValue())),
                                    (l, r) -> {l.addAll(r); return l;}));


                                    But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.



                                    This is a job for the groupingBy collector shown in the other answers or do it shorter without a stream:



                                    Map<String, Set<Apple>> res = new HashMap<>();
                                    map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));





                                    share|improve this answer














                                    if you want to proceed with toMap you can get the result as follows:



                                    map.entrySet()
                                    .stream()
                                    .collect(toMap(s -> s.getValue().getColour(),
                                    v -> new HashSet<>(singleton(v.getValue())),
                                    (l, r) -> {l.addAll(r); return l;}));


                                    But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.



                                    This is a job for the groupingBy collector shown in the other answers or do it shorter without a stream:



                                    Map<String, Set<Apple>> res = new HashMap<>();
                                    map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited 11 mins ago

























                                    answered 17 mins ago









                                    Aomine

                                    39.8k73770




                                    39.8k73770






























                                        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%2f54005438%2fconvert-mapstring-object-to-mapstring-setobject-with-filter-and-streams%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

                                        Eastern Orthodox Church

                                        Zagreb

                                        Understanding the information contained in the Deep Space Network XML data?