December 4, 2018

Simple implementation for Callable interface in Java, using lambda.

In this tutorial, we will learn basic implementations for Callable interface  using lambda in java.

Anonymous Class providing an implementation for Callable interface.

Callable<String> callMyName = new Callable<String>() {
    public String call() throws Exception {
        return "Anurag Anand";

You can submit the above implementation to return any string value. The same can be done for any other primitive type or Object type.

Case 1: Implement a callable which returns a string

Callable<String> callMyName = () -> "Anurag Anand";

Case 2 : Implement a callable which returns an int

Callable<Integer> callMyName = () -> 1;

Case 3 : Implement a callable which returns a long

Callable<Long> callMyName = () -> 1L;

Case 4 : Implement a callable to return an Object of Long type

Callable<Long> callMyName = () -> new Long(10);

The same way as above, we can return different types of object and different types of primitive in lambda.

For a complex implementation,you can take a look at this.