- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we write Callable as a lambda expression in Java?
A Callable interface defined in java.util.concurrent package. An object of Callable returns a computed result done by a thread in contrast to a Runnable interface that can only run the thread. The Callable object returns Future object that provides methods to monitor the progress of a task executed by a thread. An object of the Future used to check the status of a Callable interface and retrieves the result from Callable once the thread has done.
In the below example, we can write a Callable interface as a Lambda Expression.
Example
import java.util.concurrent.*; public class LambdaCallableTest { public static void main(String args[]) throws InterruptedException { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable c = () -> { // Lambda Expression int n = 0; for(int i = 0; i < 100; i++) { n += i; } return n; }; Future<Integer> future = executor.submit(c); try { Integer result = future.get(); //wait for a thread to complete System.out.println(result); } catch(ExecutionException e) { e.printStackTrace(); } executor.shutdown(); } }
Output
4950
- Related Articles
- How can we write a multiline lambda expression in Java?
- How to write the comparator as a lambda expression in Java?
- How can we pass lambda expression in a method in Java?
- How to write a conditional expression in lambda expression in Java?
- What kind of variables can we access in a lambda expression in Java?
- How many parameters can a lambda expression have in Java?
- How to write lambda expression code for SwingUtilities.invokeLater in Java?
- How to pass a lambda expression as a method parameter in Java?
- How can we iterate the elements of List and Map using lambda expression in Java?
- Java Program to pass lambda expression as a method argument
- Can we sort a list with Lambda in Java?
- Lambda expression in Java 8
- How to declare a variable within lambda expression in Java?
- How to reverse a string using lambda expression in Java?
- How can we use lambda expressions with functional interfaces in Java?

Advertisements