# Chain of CompletableFutures in Java

I am new to this CompletableFuture function in Java. I have the following code below that works fine but looks quite messy IMHO.

CompletableFuture<String> cf = CompletableFuture.completedFuture(isRQMRunning_3);

if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(startRQM_4);

if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(pendingChangesStatus);

if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(acceptPendingChanges_8);

if(cf.isDone()) {
System.out.println("Value- " + cf.get());

if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(acceptPendingChanges_8);

if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(fixConflicts_9);

if(cf.isDone()) {
System.out.println("Value- " + cf.get());
}
}
}
}
}
}
}


Is it possible to make that look a lot nicer/easier to read?

You have a lot of repetition in your code. The only thing different with the 2 lines of code repeated over and over is the argument.

You could put all of these arguments into a list and iterate over them, running those 2 lines of code for each:

List<String> states = Arrays.asList(isRQMRunning_3, startRQM_4,
pendingChangesStatus, acceptPendingChanges_8,

for (String state : states)
{
// Loop until array is complete
CompletableFuture<String> cf = CompletableFuture.completedFuture(state);

if (!cf.isDone())
{
break;
}

System.out.println("Value- " + cf.get());
}

• Great suggestion @dustytrash! However, i am in need of also including the batDir with each. – StealthRT Sep 10 at 15:10
• would it just need to be this CompletableFuture.completedFuture(steps(state, batDir));? – StealthRT Sep 10 at 15:13
• Also, should if (!cf.isDone()) { be if (cf.isDone()) {? If its done then break out, right? – StealthRT Sep 10 at 15:27
• @StealthRT no, if it's done you want to continue. You stop once isDone returns false. What I wrote should do the exact same thing your code does. – dustytrash Sep 10 at 15:28