How do I create two different compliementary lists using same input












9














In my previous question - How to filter the age while grouping in map with list I was able to find the name to age groups using List<User> users. Now I am trying to find the different User groups from ages according to the threshold. I tried this



List<User> userAboveThreshold = users.stream().filter(u -> u.getAge() > 21).collect(toList());
List<User> userBelowThreshold = users.stream().filter(u -> u.getAge() <= 21).collect(toList());


This time it works I can see using



userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));


But I have to access the users list again to find the complimentary list. Can this not be done simpler?










share|improve this question



























    9














    In my previous question - How to filter the age while grouping in map with list I was able to find the name to age groups using List<User> users. Now I am trying to find the different User groups from ages according to the threshold. I tried this



    List<User> userAboveThreshold = users.stream().filter(u -> u.getAge() > 21).collect(toList());
    List<User> userBelowThreshold = users.stream().filter(u -> u.getAge() <= 21).collect(toList());


    This time it works I can see using



    userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
    userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));


    But I have to access the users list again to find the complimentary list. Can this not be done simpler?










    share|improve this question

























      9












      9








      9


      2





      In my previous question - How to filter the age while grouping in map with list I was able to find the name to age groups using List<User> users. Now I am trying to find the different User groups from ages according to the threshold. I tried this



      List<User> userAboveThreshold = users.stream().filter(u -> u.getAge() > 21).collect(toList());
      List<User> userBelowThreshold = users.stream().filter(u -> u.getAge() <= 21).collect(toList());


      This time it works I can see using



      userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
      userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));


      But I have to access the users list again to find the complimentary list. Can this not be done simpler?










      share|improve this question













      In my previous question - How to filter the age while grouping in map with list I was able to find the name to age groups using List<User> users. Now I am trying to find the different User groups from ages according to the threshold. I tried this



      List<User> userAboveThreshold = users.stream().filter(u -> u.getAge() > 21).collect(toList());
      List<User> userBelowThreshold = users.stream().filter(u -> u.getAge() <= 21).collect(toList());


      This time it works I can see using



      userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
      userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));


      But I have to access the users list again to find the complimentary list. Can this not be done simpler?







      java java-stream






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 20 at 13:26









      Mani

      2281319




      2281319
























          2 Answers
          2






          active

          oldest

          votes


















          7














          List.removeAll



          You can use removeAll to obtain the complimentary list.



          List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
          userBelowThreshold.removeAll(userAboveThreshold);


          Note: This would require overridden equals and hashCode implementation for User.





          Collectors.partitioningBy



          On the other hand, if you further want to iterate over the complete users list just once, you can use Collectors.partitioningBy as:



          Map<Boolean, List<User>> userAgeMap = users.stream()
          .collect(Collectors.partitioningBy(user -> user.getAge() > 21, Collectors.toList()));
          List<User> userAboveThreshold = userAgeMap.get(Boolean.TRUE);
          List<User> userBelowThreshold = userAgeMap.get(Boolean.FALSE);





          share|improve this answer



















          • 1




            For those concerned about the cost of using a map here, worry not, Collectors.partitioningBy returns a custom map class that stores the 2 partitions (holding the the true and false member) directly inline.
            – Alexander
            Dec 20 at 18:47



















          6














          You're after the partitioningBy collector:



          Map<Boolean, List<User>> result = 
          users.stream().collect(partitioningBy(u -> u.getAge() > 21));


          Then use it as follows:



          List<User> userAboveThreshold = result.get(true);
          List<User> userBelowThreshold = result.get(false);





          share|improve this answer

















          • 2




            @Mani well you should also know that internally it uses a specialized map with two keys only, faster look-up then a HashMap for example
            – Eugene
            Dec 20 at 13:58











          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%2f53869662%2fhow-do-i-create-two-different-compliementary-lists-using-same-input%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          7














          List.removeAll



          You can use removeAll to obtain the complimentary list.



          List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
          userBelowThreshold.removeAll(userAboveThreshold);


          Note: This would require overridden equals and hashCode implementation for User.





          Collectors.partitioningBy



          On the other hand, if you further want to iterate over the complete users list just once, you can use Collectors.partitioningBy as:



          Map<Boolean, List<User>> userAgeMap = users.stream()
          .collect(Collectors.partitioningBy(user -> user.getAge() > 21, Collectors.toList()));
          List<User> userAboveThreshold = userAgeMap.get(Boolean.TRUE);
          List<User> userBelowThreshold = userAgeMap.get(Boolean.FALSE);





          share|improve this answer



















          • 1




            For those concerned about the cost of using a map here, worry not, Collectors.partitioningBy returns a custom map class that stores the 2 partitions (holding the the true and false member) directly inline.
            – Alexander
            Dec 20 at 18:47
















          7














          List.removeAll



          You can use removeAll to obtain the complimentary list.



          List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
          userBelowThreshold.removeAll(userAboveThreshold);


          Note: This would require overridden equals and hashCode implementation for User.





          Collectors.partitioningBy



          On the other hand, if you further want to iterate over the complete users list just once, you can use Collectors.partitioningBy as:



          Map<Boolean, List<User>> userAgeMap = users.stream()
          .collect(Collectors.partitioningBy(user -> user.getAge() > 21, Collectors.toList()));
          List<User> userAboveThreshold = userAgeMap.get(Boolean.TRUE);
          List<User> userBelowThreshold = userAgeMap.get(Boolean.FALSE);





          share|improve this answer



















          • 1




            For those concerned about the cost of using a map here, worry not, Collectors.partitioningBy returns a custom map class that stores the 2 partitions (holding the the true and false member) directly inline.
            – Alexander
            Dec 20 at 18:47














          7












          7








          7






          List.removeAll



          You can use removeAll to obtain the complimentary list.



          List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
          userBelowThreshold.removeAll(userAboveThreshold);


          Note: This would require overridden equals and hashCode implementation for User.





          Collectors.partitioningBy



          On the other hand, if you further want to iterate over the complete users list just once, you can use Collectors.partitioningBy as:



          Map<Boolean, List<User>> userAgeMap = users.stream()
          .collect(Collectors.partitioningBy(user -> user.getAge() > 21, Collectors.toList()));
          List<User> userAboveThreshold = userAgeMap.get(Boolean.TRUE);
          List<User> userBelowThreshold = userAgeMap.get(Boolean.FALSE);





          share|improve this answer














          List.removeAll



          You can use removeAll to obtain the complimentary list.



          List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
          userBelowThreshold.removeAll(userAboveThreshold);


          Note: This would require overridden equals and hashCode implementation for User.





          Collectors.partitioningBy



          On the other hand, if you further want to iterate over the complete users list just once, you can use Collectors.partitioningBy as:



          Map<Boolean, List<User>> userAgeMap = users.stream()
          .collect(Collectors.partitioningBy(user -> user.getAge() > 21, Collectors.toList()));
          List<User> userAboveThreshold = userAgeMap.get(Boolean.TRUE);
          List<User> userBelowThreshold = userAgeMap.get(Boolean.FALSE);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 20 at 13:37

























          answered Dec 20 at 13:27









          nullpointer

          41.1k1086173




          41.1k1086173








          • 1




            For those concerned about the cost of using a map here, worry not, Collectors.partitioningBy returns a custom map class that stores the 2 partitions (holding the the true and false member) directly inline.
            – Alexander
            Dec 20 at 18:47














          • 1




            For those concerned about the cost of using a map here, worry not, Collectors.partitioningBy returns a custom map class that stores the 2 partitions (holding the the true and false member) directly inline.
            – Alexander
            Dec 20 at 18:47








          1




          1




          For those concerned about the cost of using a map here, worry not, Collectors.partitioningBy returns a custom map class that stores the 2 partitions (holding the the true and false member) directly inline.
          – Alexander
          Dec 20 at 18:47




          For those concerned about the cost of using a map here, worry not, Collectors.partitioningBy returns a custom map class that stores the 2 partitions (holding the the true and false member) directly inline.
          – Alexander
          Dec 20 at 18:47













          6














          You're after the partitioningBy collector:



          Map<Boolean, List<User>> result = 
          users.stream().collect(partitioningBy(u -> u.getAge() > 21));


          Then use it as follows:



          List<User> userAboveThreshold = result.get(true);
          List<User> userBelowThreshold = result.get(false);





          share|improve this answer

















          • 2




            @Mani well you should also know that internally it uses a specialized map with two keys only, faster look-up then a HashMap for example
            – Eugene
            Dec 20 at 13:58
















          6














          You're after the partitioningBy collector:



          Map<Boolean, List<User>> result = 
          users.stream().collect(partitioningBy(u -> u.getAge() > 21));


          Then use it as follows:



          List<User> userAboveThreshold = result.get(true);
          List<User> userBelowThreshold = result.get(false);





          share|improve this answer

















          • 2




            @Mani well you should also know that internally it uses a specialized map with two keys only, faster look-up then a HashMap for example
            – Eugene
            Dec 20 at 13:58














          6












          6








          6






          You're after the partitioningBy collector:



          Map<Boolean, List<User>> result = 
          users.stream().collect(partitioningBy(u -> u.getAge() > 21));


          Then use it as follows:



          List<User> userAboveThreshold = result.get(true);
          List<User> userBelowThreshold = result.get(false);





          share|improve this answer












          You're after the partitioningBy collector:



          Map<Boolean, List<User>> result = 
          users.stream().collect(partitioningBy(u -> u.getAge() > 21));


          Then use it as follows:



          List<User> userAboveThreshold = result.get(true);
          List<User> userBelowThreshold = result.get(false);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 20 at 13:26









          Aomine

          38.8k73365




          38.8k73365








          • 2




            @Mani well you should also know that internally it uses a specialized map with two keys only, faster look-up then a HashMap for example
            – Eugene
            Dec 20 at 13:58














          • 2




            @Mani well you should also know that internally it uses a specialized map with two keys only, faster look-up then a HashMap for example
            – Eugene
            Dec 20 at 13:58








          2




          2




          @Mani well you should also know that internally it uses a specialized map with two keys only, faster look-up then a HashMap for example
          – Eugene
          Dec 20 at 13:58




          @Mani well you should also know that internally it uses a specialized map with two keys only, faster look-up then a HashMap for example
          – Eugene
          Dec 20 at 13:58


















          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%2f53869662%2fhow-do-i-create-two-different-compliementary-lists-using-same-input%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

          Сан-Квентин

          8-я гвардейская общевойсковая армия

          Алькесар