Tuesday, April 30, 2019

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 ").
        // submit method
        Future<String> f = es.submit(callableObj);
        try {
            System.out.println("" + f.get());
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block



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 8
  4. Functional Interface Annotation in Java
  5. Java Lambda Expressions Interview Questions

You may also like-

  1. How to Convert Date And Time Between Different Time-Zones in Java
  2. How to Convert a File to Byte Array
  3. Java Concurrency Interview Questions
  4. Executor and ExecutorService in Java concurrency
  5. Difference between Comparable and Comparator
  6. String join() method in Java 8
  7. interface default methods in Java 8
  8. What is Dependency Injection in Spring

No comments:

Post a Comment