Core Java

Java 8 CompletableFuture thenApply Example

Hello. In this tutorial, we will explore the Java 8 CompletableFuture thenApply method.

1. Introduction

Java 8 CompletableFuture thenApply

Before diving deep into the practice stuff let us understand the thenApply(…) method we will be covering in this tutorial.

  • CompletableFuture.thenApply(…) method is inherited from the CompletionStage
  • The method returns a new CompletionStage (is a Promise object) that when the stage is completed normally, is executed with the stage’s result as an argument to the supplied function
  • The method is represented by the syntax – <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn)
  • The method is used to perform some extra task on the result of another task

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Understanding thenApply() method

Create a test class in the com.java8 package and add the following code to it. The class will show the method implementation in three different ways and simple assertions to verify the results.

DemoTest.java

package com.java8;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Test;

// CompletableFuture.thenApply() is inherited from CompletionStage.
// this method returns a new CompletionStage that when the stage completes normally is executed
// with this stage's result as the argument of the supplied function

class DemoTest {

  static final Random RANDOM = new Random();

  @Test
  void test_thenApplyDemo() throws ExecutionException, InterruptedException {
    CompletableFuture<String> c =
        CompletableFuture.supplyAsync(() -> "hello")
            .thenApply((data) -> {
              String result = "";
              try {
                result = delayedUpperCase(data) + " WORLD";
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              return result;
            });

    assertEquals("HELLO WORLD", c.get());
  }

  private String delayedUpperCase(String result) throws InterruptedException {
    Thread.sleep(1000);
    return result.toUpperCase();
  }

  @Test
  void test_thenApplyDemo1() throws ExecutionException, InterruptedException {
    int num1 = RANDOM.nextInt();
    int num2 = RANDOM.nextInt();

    CompletableFuture<String> c =
        CompletableFuture.supplyAsync(() -> multiply(num1, num2))
            .thenApply(this::print);

    String expected = "Result: " + (num1 * num2);
    assertEquals(expected, c.get());
  }

  private int multiply(int num1, int num2) {
    return num1 * num2;
  }

  private String print(int result) {
    return "Result: " + result;
  }
}

Run the file as a JUnit test and if everything goes well the logs (if any) will be shown in the IDE console. All the test cases should pass. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned thenApply(…) method introduced in java8 programming. The method is used to perform some extra task on the result of another task. You can download the source code from the Downloads section.

4. Download the Project

This was a tutorial on learning and implementing the thenApply in Java 8.

Download
You can download the full source code of this example here: Java 8 CompletableFuture thenApply Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button