Thursday, 25 August 2016

Lambda Expression Callable example

Since Callable is a functional interface, starting Java 8 it can also be implemented as a lambda expression.

In this post we’ll see how to implement Callable as a lambda expression. 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 Lambda Expression Callable example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Lambda Expression Runnable example
  2. Lambda Expression Comparator example
  3. Functional interface annotation in Java 8
  4. Lambda expression examples in Java 8
  5. Java Concurrency interview questions

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment