Saturday, May 14, 2022

Java Lambda Expression Callable Example

Since Callable is a functional interface, Java 8 onward it can also be implemented as a lambda expression. This post shows how you can implement Callable interface as a lambda expression in Java.

Suppose you want to have a callable where string is passed and it returns the length of the string.
In this Java code a thread pool of 2 threads is created and then submit method is called with callable object as parameter.

Java Code

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableLambda {
  public static void main(String args[]){
    ExecutorService es = Executors.newFixedThreadPool(2);
    getLength(es, "executor");
    getLength(es, "executor service");
    getLength(es, "Scheduled executor service");
    getLength(es, "executors");
    getLength(es, "fork join");
    getLength(es, "callable");    
  }
    
  public static void getLength(ExecutorService es, final String str){
    // callable implemented as lambda expression
    Callable<String> callableObj = () -> {
      StringBuffer sb = new StringBuffer();
      return (sb.append("Length of string ").append(str).append(" is ").
              append(str.length())).toString();
    };
        
    // submit method
    Future<String> f = es.submit(callableObj);
    
    try {
      System.out.println("" + f.get());
    } catch (InterruptedException | ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Length of string executor is 8
Length of string executor service is 16
Length of string Scheduled executor service is 26
Length of string executors is 9
Length of string fork join is 9
Length of string callable is 8

Also, if you noticed the  try-catch block in the code,  multi catch statement from Java 7 is used here.

That's all for this topic Java Lambda Expression Callable Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Lambda Expression Runnable Example
  2. Java Lambda Expression Comparator Example
  3. Lambda Expression Examples in Java
  4. Functional Interface Annotation in Java
  5. Java Lambda Expressions Interview Questions And Answers

You may also like-

  1. How to Convert Date And Time Between Different Time-Zones in Java
  2. Java Program to Convert a File to Byte Array
  3. Java Concurrency Interview Questions And Answers
  4. Executor And ExecutorService in Java With Examples
  5. Difference Between Comparable and Comparator in Java
  6. Java join() Method - Joining Strings
  7. Interface Default Methods in Java
  8. Dependency Injection in Spring Framework

No comments:

Post a Comment