![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements