0

I have given list in java

List<String> list;

And I have a function which takes String and gives CompletionStage. I want to iterate through list and process each task sequentially, That is when one task gives result then only i want to schedule next task from list. Is there a way to do this asynchronously without calling .get()

I also want ability to stop somewhere midway on this, depending upon the result of previous task.

hridayesh
  • 1,123
  • 1
  • 14
  • 36
  • if you will wait for the result of the current task why do you not implement it singlethreaded instead of futures? – kerberos84 Sep 22 '17 at 08:05
  • to save resources? otherwise thread will be blocked. – hridayesh Sep 22 '17 at 08:10
  • Since you want to run tasks sequentially one Thread should be enough for this. If you want to process other things at the same time you run all your tasks in a seperate one Thread and keep your main thread running. – kerberos84 Sep 22 '17 at 08:21
  • I don't know how it works internally in java. I thought we can call some http api and while waiting for response, not even one thread will be blocked! Btw I have also found solution for that. – hridayesh Sep 22 '17 at 08:29

2 Answers2

1
// Starting off like this means the loop doesn't need to special case the first iteration
CompletionStage<Result> stage = CompletableFuture.completedFuture(null);
for (String str : list) {
    stage = stage.thenCompose(result -> shouldStop(result) ? result : yourFunction(str));
}

The end result of this is that stage is the very end of a long sequence of CompletionStage objects all chained together. Each stage in the sequence will execute only when the previous stage is complete, because that's how thenCompose (and all the CompletionStage chaining methods) works. Each stage will call your function and pass the result on to the next stage - until you get the result you want to stop on, at which point the shouldStop check will make all the remaining stages just pass that result through until stage itself is completed with that result value.

Douglas
  • 5,017
  • 1
  • 14
  • 28
-1

You can loop into your list using a customized for loop, and then inside the for loop, you can do whatever you want, like continue, break,...

here is an example of how you can loop through a list in java:

List<String> list;//here assumed that you already initialized your list

for(String l: list) {//here each element of list is called l
//Do what ever you want to do here
System.out.println("single element of list: "+ l);
}

Hope this is what you're looking for. update me if it works or not for modifications

Freddy Sop
  • 117
  • 1
  • 1
  • 8