CompletableFuture in Java 8 Explained in 5 Minutes | Interview Ready

 Hi All,

Today I have released new video on "CompletableFuture in Java 8 Explained in 5 Minutes | Interview Ready"

This is frequently asked question in Java Interview.

Please watch full video, share, like and Subscribe Youtube channel and press bell icon. So you will get latest video notification.






 package org.practice.basicprgms;


import java.util.Arrays;

import java.util.concurrent.CompletableFuture;

import java.util.concurrent.ExecutionException;

import java.util.stream.IntStream;


public class CompletableFutureDemo {


public static void main(String[] args) throws InterruptedException, ExecutionException {

// 1. Count Even Numbers using supplyAsync()

int[] arr = {10,15,20,25,30};

CompletableFuture<Long> future =

CompletableFuture.supplyAsync(() ->

Arrays.stream(arr)

.filter(n -> n % 2 == 0)

.count());

System.out.println("Even Numbers : "+ future.get());

// 2. Print Odd Numbers Using runAsync()

CompletableFuture.runAsync(() ->

IntStream.rangeClosed(11, 20)

.filter(n -> n % 2 != 0)

.forEach(System.out::println));

try {

Thread.sleep(1000);

}catch(Exception e) {}


// 3. Combine Two Numbers using supplyAsync and thenCombine method

CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 10);

CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 20);

CompletableFuture<Integer> result =

f1.thenCombine(f2, Integer::sum);

System.out.println("Sum of f1 and f2 = "+ result.get());


// 4. Calculate 12 Months Salary Using supplyAsync and thenApply

CompletableFuture<Double> future1 =

CompletableFuture.supplyAsync(() -> 50000.00)

.thenApply(salary -> salary * 12);

System.out.println("Annual Salary = "+ future1.get());


// 5. Calculate 1 Months Salary and Add Bonus using supplyAsync and thenAccept

//CompletableFuture<Double> future2 =

CompletableFuture.supplyAsync(() -> 50000.00)

.thenAccept(salary -> {

double finalSalary = salary + 100000;

System.out.println("Salary with Bonus : "+ finalSalary);

});


// 6. Calculate 12 Months Salary and Add Bonus using method chaining of supplyAsync, thenApply and thenAccept

CompletableFuture.supplyAsync(() -> 50000.00)

.thenApply(salary -> salary * 12)

.thenApply(salary -> salary + 100000)

.thenAccept(salary -> System.out.println("Annual Salary with Bonus : "+ salary));


}


}


output:

Even Numbers : 3

11

13

15

17

19

Sum of f1 and f2 = 30

Annual Salary = 600000.0

Salary with Bonus : 150000.0

Annual Salary with Bonus : 700000.0



Post a Comment

0 Comments