Defining Callable Tasks with Lambda Expressions
You'll learn how to write Callable tasks concisely using lambda expressions and method references instead of verbose anonymous classes.
The Verbose Way vs The Lambda Way
In earlier lessons, you learned that Callable<V> is a functional interface with a single abstract method: V call() throws Exception. This makes it a perfect candidate for lambda expressions.
Instead of writing a full anonymous class:
Callable<Integer> task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 42 * 2;
}
};
You can use a lambda expression to achieve the same result in one line:
Callable<Integer> task = () -> 42 * 2;
Lambda Syntax for Callable
Since call() takes no parameters, your lambda starts with empty parentheses (), followed by the arrow ->, then the expression or block that produces the result:
// Simple expression
Callable<String> simpleTask = () -> "Hello from Callable";
// Block with multiple statements
Callable<Double> complexTask = () -> {
double result = Math.random() * 100;
Thread.sleep(1000);
return result;
};
Method References for Existing Methods
If your computation already exists as a method, you can use a method reference:
Callable<Double> randomTask = Math::random;
Callable<String> readTask = () -> someObject.fetchData();
Analogy: Lambda expressions are like shorthand notation in math—instead of writing "the function f that takes x and returns x²," you write "f(x) = x²." Both describe the same thing, but one is far more concise.
Key Takeaway: Lambda expressions and method references allow you to define Callable tasks inline with minimal syntax, making asynchronous code cleaner and more readable while preserving all the functionality of traditional anonymous classes.