Chaining completable futures based on conditionsEclipse/Java code completion not workingBeginner's Java - Help Needed Using EclipseFIlling a 2D array with random integers javaJava HiLo program stopssum of integers. add them. check if sum is odd or even. print the sum of digits and also print if odd or evenjava completable futures and exception chainingRandom Number Sort ArraysMigrating async task executor to use chained CompletableFutureFell on the goallineHow to handle error responses from in any step of a completable future chain?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

What do the dots in this tr command do: tr .............A-Z A-ZA-Z <<< "JVPQBOV" (with 13 dots)

Email Account under attack (really) - anything I can do?

How does strength of boric acid solution increase in presence of salicylic acid?

What do you call a Matrix-like slowdown and camera movement effect?

The use of multiple foreign keys on same column in SQL Server

Is this a crack on the carbon frame?

Is it possible to do 50 km distance without any previous training?

Have astronauts in space suits ever taken selfies? If so, how?

If I cast Expeditious Retreat, can I Dash as a bonus action on the same turn?

Why not use SQL instead of GraphQL?

What's the point of deactivating Num Lock on login screens?

How can I make my BBEG immortal short of making them a Lich or Vampire?

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

Is a tag line useful on a cover?

Can a Warlock become Neutral Good?

Writing rule stating superpower from different root cause is bad writing

Why are electrically insulating heatsinks so rare? Is it just cost?

Maximum likelihood parameters deviate from posterior distributions

Dragon forelimb placement

How much RAM could one put in a typical 80386 setup?

Why dont electromagnetic waves interact with each other?

Fencing style for blades that can attack from a distance

Why do falling prices hurt debtors?



Chaining completable futures based on conditions


Eclipse/Java code completion not workingBeginner's Java - Help Needed Using EclipseFIlling a 2D array with random integers javaJava HiLo program stopssum of integers. add them. check if sum is odd or even. print the sum of digits and also print if odd or evenjava completable futures and exception chainingRandom Number Sort ArraysMigrating async task executor to use chained CompletableFutureFell on the goallineHow to handle error responses from in any step of a completable future chain?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am having a bunch of methods that return a CompletableFuture and I would like to chain in a specific way



package com.sandbox;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;

public class SandboxFutures

public CompletableFuture<Integer> generateRandom(int min, int max)
return CompletableFuture.supplyAsync(() ->
if (min >= max)
throw new IllegalArgumentException("max must be greater than min");


Random r = new Random();
return r.nextInt((max - min) + 1) + min;
);


public CompletableFuture<String> printEvenOrOdd(int result)
return CompletableFuture.supplyAsync(() ->
if (result % 2 == 0)
return "Even";
else
return "Odd";
);


public CompletableFuture<Integer> findFactorial(int evenNumber)
return CompletableFuture.supplyAsync(() ->
if (evenNumber <= 0)
return 0;


return IntStream.rangeClosed(2, evenNumber).reduce(1, (x,y) -> x*y);
);


public CompletableFuture<Integer> convertToNearestEvenInteger(int oddNumber)
return CompletableFuture.supplyAsync(() ->
if (oddNumber <= 0)
return 2;

return oddNumber+1;
);





I am trying to combine them based on the following rules,



  1. Generate a random number between 1 and 100

  2. If the number is even print Even, if it is odd print Odd

  3. If the number is even call the findFactorial with the random number

  4. If the number is odd find the nearest even via convertToNearestEvenInteger

I am not too clear on how to do the conditional chaining and exception handling. Some examples or code snippets may be helpful.










share|improve this question






























    1















    I am having a bunch of methods that return a CompletableFuture and I would like to chain in a specific way



    package com.sandbox;

    import java.util.Random;
    import java.util.concurrent.CompletableFuture;
    import java.util.stream.IntStream;

    public class SandboxFutures

    public CompletableFuture<Integer> generateRandom(int min, int max)
    return CompletableFuture.supplyAsync(() ->
    if (min >= max)
    throw new IllegalArgumentException("max must be greater than min");


    Random r = new Random();
    return r.nextInt((max - min) + 1) + min;
    );


    public CompletableFuture<String> printEvenOrOdd(int result)
    return CompletableFuture.supplyAsync(() ->
    if (result % 2 == 0)
    return "Even";
    else
    return "Odd";
    );


    public CompletableFuture<Integer> findFactorial(int evenNumber)
    return CompletableFuture.supplyAsync(() ->
    if (evenNumber <= 0)
    return 0;


    return IntStream.rangeClosed(2, evenNumber).reduce(1, (x,y) -> x*y);
    );


    public CompletableFuture<Integer> convertToNearestEvenInteger(int oddNumber)
    return CompletableFuture.supplyAsync(() ->
    if (oddNumber <= 0)
    return 2;

    return oddNumber+1;
    );





    I am trying to combine them based on the following rules,



    1. Generate a random number between 1 and 100

    2. If the number is even print Even, if it is odd print Odd

    3. If the number is even call the findFactorial with the random number

    4. If the number is odd find the nearest even via convertToNearestEvenInteger

    I am not too clear on how to do the conditional chaining and exception handling. Some examples or code snippets may be helpful.










    share|improve this question


























      1












      1








      1








      I am having a bunch of methods that return a CompletableFuture and I would like to chain in a specific way



      package com.sandbox;

      import java.util.Random;
      import java.util.concurrent.CompletableFuture;
      import java.util.stream.IntStream;

      public class SandboxFutures

      public CompletableFuture<Integer> generateRandom(int min, int max)
      return CompletableFuture.supplyAsync(() ->
      if (min >= max)
      throw new IllegalArgumentException("max must be greater than min");


      Random r = new Random();
      return r.nextInt((max - min) + 1) + min;
      );


      public CompletableFuture<String> printEvenOrOdd(int result)
      return CompletableFuture.supplyAsync(() ->
      if (result % 2 == 0)
      return "Even";
      else
      return "Odd";
      );


      public CompletableFuture<Integer> findFactorial(int evenNumber)
      return CompletableFuture.supplyAsync(() ->
      if (evenNumber <= 0)
      return 0;


      return IntStream.rangeClosed(2, evenNumber).reduce(1, (x,y) -> x*y);
      );


      public CompletableFuture<Integer> convertToNearestEvenInteger(int oddNumber)
      return CompletableFuture.supplyAsync(() ->
      if (oddNumber <= 0)
      return 2;

      return oddNumber+1;
      );





      I am trying to combine them based on the following rules,



      1. Generate a random number between 1 and 100

      2. If the number is even print Even, if it is odd print Odd

      3. If the number is even call the findFactorial with the random number

      4. If the number is odd find the nearest even via convertToNearestEvenInteger

      I am not too clear on how to do the conditional chaining and exception handling. Some examples or code snippets may be helpful.










      share|improve this question
















      I am having a bunch of methods that return a CompletableFuture and I would like to chain in a specific way



      package com.sandbox;

      import java.util.Random;
      import java.util.concurrent.CompletableFuture;
      import java.util.stream.IntStream;

      public class SandboxFutures

      public CompletableFuture<Integer> generateRandom(int min, int max)
      return CompletableFuture.supplyAsync(() ->
      if (min >= max)
      throw new IllegalArgumentException("max must be greater than min");


      Random r = new Random();
      return r.nextInt((max - min) + 1) + min;
      );


      public CompletableFuture<String> printEvenOrOdd(int result)
      return CompletableFuture.supplyAsync(() ->
      if (result % 2 == 0)
      return "Even";
      else
      return "Odd";
      );


      public CompletableFuture<Integer> findFactorial(int evenNumber)
      return CompletableFuture.supplyAsync(() ->
      if (evenNumber <= 0)
      return 0;


      return IntStream.rangeClosed(2, evenNumber).reduce(1, (x,y) -> x*y);
      );


      public CompletableFuture<Integer> convertToNearestEvenInteger(int oddNumber)
      return CompletableFuture.supplyAsync(() ->
      if (oddNumber <= 0)
      return 2;

      return oddNumber+1;
      );





      I am trying to combine them based on the following rules,



      1. Generate a random number between 1 and 100

      2. If the number is even print Even, if it is odd print Odd

      3. If the number is even call the findFactorial with the random number

      4. If the number is odd find the nearest even via convertToNearestEvenInteger

      I am not too clear on how to do the conditional chaining and exception handling. Some examples or code snippets may be helpful.







      java asynchronous exception completable-future conditional-execution






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 4:48









      John Kugelman

      248k54406460




      248k54406460










      asked Mar 8 at 4:24









      g0c00l.g33kg0c00l.g33k

      71811132




      71811132






















          2 Answers
          2






          active

          oldest

          votes


















          0














          The way printEvenOrOdd is written makes it more difficult than it needs to be. The problem is that it doesn't print the word "Even" or "Odd", it returns it, which means the original result is lost. The rest of the steps rely on having the actual number. To work around it, you could use call printEvenOrOdd and use .thenApply(__ -> result) to restore the original number afterwards. It would look like this:



          System.out.println(
          generateRandom(1, 100)
          .thenCompose(result ->
          printEvenOrOdd(result)
          .thenAccept(System.out::println)
          .thenApply(__ -> result)
          )
          .thenCompose(result ->
          result % 2 == 0
          ? findFactorial(result)
          : convertToNearestEvenInteger(result)
          )
          .join()
          );


          A better solution would be to change the definition of printEvenOrOdd to something like:



          public CompletableFuture<Integer> printEvenOrOdd(int result) 
          return CompletableFuture.supplyAsync(() ->
          System.out.println(result % 2 == 0 ? "Even" : "Odd");
          return result;
          );



          That would make it much easier to chain steps 3 and 4:



          System.out.println(
          generateRandom(1, 100)
          .thenApply(this::printEvenOrOdd)
          .thenCompose(result ->
          result % 2 == 0
          ? findFactorial(result)
          : convertToNearestEvenInteger(result)
          )
          .join()
          );





          share|improve this answer
































            1














            You can use thenCompose():



            CompletableFuture<Integer> n = generateRandom(1, 100)
            .thenCompose(i -> printEvenOrOdd(i)
            .thenCompose(s -> s.equals("Even")
            ? findFactorial(i)
            : convertToNearestEvenInteger(i)));
            System.out.println(n.get());


            However, when big even numbers are generated, your factorial method can't store anything bigger than int, so you need to update that.






            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%2f55056706%2fchaining-completable-futures-based-on-conditions%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









              0














              The way printEvenOrOdd is written makes it more difficult than it needs to be. The problem is that it doesn't print the word "Even" or "Odd", it returns it, which means the original result is lost. The rest of the steps rely on having the actual number. To work around it, you could use call printEvenOrOdd and use .thenApply(__ -> result) to restore the original number afterwards. It would look like this:



              System.out.println(
              generateRandom(1, 100)
              .thenCompose(result ->
              printEvenOrOdd(result)
              .thenAccept(System.out::println)
              .thenApply(__ -> result)
              )
              .thenCompose(result ->
              result % 2 == 0
              ? findFactorial(result)
              : convertToNearestEvenInteger(result)
              )
              .join()
              );


              A better solution would be to change the definition of printEvenOrOdd to something like:



              public CompletableFuture<Integer> printEvenOrOdd(int result) 
              return CompletableFuture.supplyAsync(() ->
              System.out.println(result % 2 == 0 ? "Even" : "Odd");
              return result;
              );



              That would make it much easier to chain steps 3 and 4:



              System.out.println(
              generateRandom(1, 100)
              .thenApply(this::printEvenOrOdd)
              .thenCompose(result ->
              result % 2 == 0
              ? findFactorial(result)
              : convertToNearestEvenInteger(result)
              )
              .join()
              );





              share|improve this answer





























                0














                The way printEvenOrOdd is written makes it more difficult than it needs to be. The problem is that it doesn't print the word "Even" or "Odd", it returns it, which means the original result is lost. The rest of the steps rely on having the actual number. To work around it, you could use call printEvenOrOdd and use .thenApply(__ -> result) to restore the original number afterwards. It would look like this:



                System.out.println(
                generateRandom(1, 100)
                .thenCompose(result ->
                printEvenOrOdd(result)
                .thenAccept(System.out::println)
                .thenApply(__ -> result)
                )
                .thenCompose(result ->
                result % 2 == 0
                ? findFactorial(result)
                : convertToNearestEvenInteger(result)
                )
                .join()
                );


                A better solution would be to change the definition of printEvenOrOdd to something like:



                public CompletableFuture<Integer> printEvenOrOdd(int result) 
                return CompletableFuture.supplyAsync(() ->
                System.out.println(result % 2 == 0 ? "Even" : "Odd");
                return result;
                );



                That would make it much easier to chain steps 3 and 4:



                System.out.println(
                generateRandom(1, 100)
                .thenApply(this::printEvenOrOdd)
                .thenCompose(result ->
                result % 2 == 0
                ? findFactorial(result)
                : convertToNearestEvenInteger(result)
                )
                .join()
                );





                share|improve this answer



























                  0












                  0








                  0







                  The way printEvenOrOdd is written makes it more difficult than it needs to be. The problem is that it doesn't print the word "Even" or "Odd", it returns it, which means the original result is lost. The rest of the steps rely on having the actual number. To work around it, you could use call printEvenOrOdd and use .thenApply(__ -> result) to restore the original number afterwards. It would look like this:



                  System.out.println(
                  generateRandom(1, 100)
                  .thenCompose(result ->
                  printEvenOrOdd(result)
                  .thenAccept(System.out::println)
                  .thenApply(__ -> result)
                  )
                  .thenCompose(result ->
                  result % 2 == 0
                  ? findFactorial(result)
                  : convertToNearestEvenInteger(result)
                  )
                  .join()
                  );


                  A better solution would be to change the definition of printEvenOrOdd to something like:



                  public CompletableFuture<Integer> printEvenOrOdd(int result) 
                  return CompletableFuture.supplyAsync(() ->
                  System.out.println(result % 2 == 0 ? "Even" : "Odd");
                  return result;
                  );



                  That would make it much easier to chain steps 3 and 4:



                  System.out.println(
                  generateRandom(1, 100)
                  .thenApply(this::printEvenOrOdd)
                  .thenCompose(result ->
                  result % 2 == 0
                  ? findFactorial(result)
                  : convertToNearestEvenInteger(result)
                  )
                  .join()
                  );





                  share|improve this answer















                  The way printEvenOrOdd is written makes it more difficult than it needs to be. The problem is that it doesn't print the word "Even" or "Odd", it returns it, which means the original result is lost. The rest of the steps rely on having the actual number. To work around it, you could use call printEvenOrOdd and use .thenApply(__ -> result) to restore the original number afterwards. It would look like this:



                  System.out.println(
                  generateRandom(1, 100)
                  .thenCompose(result ->
                  printEvenOrOdd(result)
                  .thenAccept(System.out::println)
                  .thenApply(__ -> result)
                  )
                  .thenCompose(result ->
                  result % 2 == 0
                  ? findFactorial(result)
                  : convertToNearestEvenInteger(result)
                  )
                  .join()
                  );


                  A better solution would be to change the definition of printEvenOrOdd to something like:



                  public CompletableFuture<Integer> printEvenOrOdd(int result) 
                  return CompletableFuture.supplyAsync(() ->
                  System.out.println(result % 2 == 0 ? "Even" : "Odd");
                  return result;
                  );



                  That would make it much easier to chain steps 3 and 4:



                  System.out.println(
                  generateRandom(1, 100)
                  .thenApply(this::printEvenOrOdd)
                  .thenCompose(result ->
                  result % 2 == 0
                  ? findFactorial(result)
                  : convertToNearestEvenInteger(result)
                  )
                  .join()
                  );






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 9 at 3:23

























                  answered Mar 8 at 5:35









                  John KugelmanJohn Kugelman

                  248k54406460




                  248k54406460























                      1














                      You can use thenCompose():



                      CompletableFuture<Integer> n = generateRandom(1, 100)
                      .thenCompose(i -> printEvenOrOdd(i)
                      .thenCompose(s -> s.equals("Even")
                      ? findFactorial(i)
                      : convertToNearestEvenInteger(i)));
                      System.out.println(n.get());


                      However, when big even numbers are generated, your factorial method can't store anything bigger than int, so you need to update that.






                      share|improve this answer





























                        1














                        You can use thenCompose():



                        CompletableFuture<Integer> n = generateRandom(1, 100)
                        .thenCompose(i -> printEvenOrOdd(i)
                        .thenCompose(s -> s.equals("Even")
                        ? findFactorial(i)
                        : convertToNearestEvenInteger(i)));
                        System.out.println(n.get());


                        However, when big even numbers are generated, your factorial method can't store anything bigger than int, so you need to update that.






                        share|improve this answer



























                          1












                          1








                          1







                          You can use thenCompose():



                          CompletableFuture<Integer> n = generateRandom(1, 100)
                          .thenCompose(i -> printEvenOrOdd(i)
                          .thenCompose(s -> s.equals("Even")
                          ? findFactorial(i)
                          : convertToNearestEvenInteger(i)));
                          System.out.println(n.get());


                          However, when big even numbers are generated, your factorial method can't store anything bigger than int, so you need to update that.






                          share|improve this answer















                          You can use thenCompose():



                          CompletableFuture<Integer> n = generateRandom(1, 100)
                          .thenCompose(i -> printEvenOrOdd(i)
                          .thenCompose(s -> s.equals("Even")
                          ? findFactorial(i)
                          : convertToNearestEvenInteger(i)));
                          System.out.println(n.get());


                          However, when big even numbers are generated, your factorial method can't store anything bigger than int, so you need to update that.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 8 at 5:04

























                          answered Mar 8 at 4:34









                          KartikKartik

                          4,52231537




                          4,52231537



























                              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%2f55056706%2fchaining-completable-futures-based-on-conditions%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

                              Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                              Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                              Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved