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












7














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





























    7














    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



























      7












      7








      7


      1





      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 37 mins ago









      Aomine

      39.8k73770




      39.8k73770










      asked 1 hour ago









      M4V3N

      578




      578
























          3 Answers
          3






          active

          oldest

          votes


















          6














          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())));


          or (as Aomine commented):



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





          share|improve this answer























          • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
            – Aomine
            10 mins ago










          • @Aomine thanks.
            – Eran
            4 mins ago



















          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























          • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
            – Aomine
            10 mins ago



















          2














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



          map.values()  // get the apples
          .stream() // Stream<Apple>
          .collect(toMap(Apple::getColour, // group by colour
          v -> new HashSet<>(singleton(v)), // have values as set of apples
          (l, r) -> {l.addAll(r); return l;})); // merge colliding apples by colour


          but this is better with groupingBy and toSet as downstream:



          map.values().stream().collect(groupingBy(Apple::getColour, toSet()));


          You could also do it without a stream:



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





          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









            6














            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())));


            or (as Aomine commented):



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





            share|improve this answer























            • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
              – Aomine
              10 mins ago










            • @Aomine thanks.
              – Eran
              4 mins ago
















            6














            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())));


            or (as Aomine commented):



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





            share|improve this answer























            • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
              – Aomine
              10 mins ago










            • @Aomine thanks.
              – Eran
              4 mins ago














            6












            6








            6






            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())));


            or (as Aomine commented):



            Map<String, Set<Apple>> sortedApples = 
            appleMap.values()
            .stream()
            .collect(Collectors.groupingBy(Apple::getColour, 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())));


            or (as Aomine commented):



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






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 5 mins ago

























            answered 58 mins ago









            Eran

            279k37452537




            279k37452537












            • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
              – Aomine
              10 mins ago










            • @Aomine thanks.
              – Eran
              4 mins ago


















            • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
              – Aomine
              10 mins ago










            • @Aomine thanks.
              – Eran
              4 mins ago
















            mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
            – Aomine
            10 mins ago




            mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
            – Aomine
            10 mins ago












            @Aomine thanks.
            – Eran
            4 mins ago




            @Aomine thanks.
            – Eran
            4 mins ago













            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























            • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
              – Aomine
              10 mins ago
















            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























            • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
              – Aomine
              10 mins ago














            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 44 mins ago

























            answered 57 mins ago









            nullpointer

            42.5k1090175




            42.5k1090175












            • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
              – Aomine
              10 mins ago


















            • mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
              – Aomine
              10 mins ago
















            mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
            – Aomine
            10 mins ago




            mapping is superfluous, just pass toSet as downstream to groupingBy. see this answer
            – Aomine
            10 mins ago











            2














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



            map.values()  // get the apples
            .stream() // Stream<Apple>
            .collect(toMap(Apple::getColour, // group by colour
            v -> new HashSet<>(singleton(v)), // have values as set of apples
            (l, r) -> {l.addAll(r); return l;})); // merge colliding apples by colour


            but this is better with groupingBy and toSet as downstream:



            map.values().stream().collect(groupingBy(Apple::getColour, toSet()));


            You could also do it without a stream:



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





            share|improve this answer




























              2














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



              map.values()  // get the apples
              .stream() // Stream<Apple>
              .collect(toMap(Apple::getColour, // group by colour
              v -> new HashSet<>(singleton(v)), // have values as set of apples
              (l, r) -> {l.addAll(r); return l;})); // merge colliding apples by colour


              but this is better with groupingBy and toSet as downstream:



              map.values().stream().collect(groupingBy(Apple::getColour, toSet()));


              You could also do it without a stream:



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





              share|improve this answer


























                2












                2








                2






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



                map.values()  // get the apples
                .stream() // Stream<Apple>
                .collect(toMap(Apple::getColour, // group by colour
                v -> new HashSet<>(singleton(v)), // have values as set of apples
                (l, r) -> {l.addAll(r); return l;})); // merge colliding apples by colour


                but this is better with groupingBy and toSet as downstream:



                map.values().stream().collect(groupingBy(Apple::getColour, toSet()));


                You could also do it without a stream:



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





                share|improve this answer














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



                map.values()  // get the apples
                .stream() // Stream<Apple>
                .collect(toMap(Apple::getColour, // group by colour
                v -> new HashSet<>(singleton(v)), // have values as set of apples
                (l, r) -> {l.addAll(r); return l;})); // merge colliding apples by colour


                but this is better with groupingBy and toSet as downstream:



                map.values().stream().collect(groupingBy(Apple::getColour, toSet()));


                You could also do it without a stream:



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






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 14 mins ago

























                answered 44 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

                    Morgemoulin

                    Scott Moir

                    Souastre