Sunday, 13 May 2018

Lambda Expression to run a task

In this post, I am going to define a functional interface that is like Runnable interface and allows you to throw a checked exception.

Task.java
package com.sample.functional.interfaces;

/**
 * 
 * It is a functional interface similar to {@link Runnable} interface and allows you to throw checked exception.
 * 
 * @author Krishna
 *
 */
public interface Task {

 /**
  * Execute the task.
  * 
  * @throws Exception
  */
 public void run() throws Exception;
}

Application.java
package com.sample.app;

import com.sample.functional.interfaces.Task;

public class Application {

 private static void executeTask(Task task) throws Exception {
  task.run();
 }

 public static void main(String args[]) throws Exception {
  executeTask(() -> {
   System.out.println("Simple hello World Application");
  });

  executeTask(() -> {
   int a = 10;
   int b = 20;
   String result = String.format("Sum of %d, and %d is %d", a, b, (a + b));
   System.out.println(result);
  });
 }
}


Output
Simple hello World Application
Sum of 10, and 20 is 30





Previous                                                 Next                                                 Home

No comments:

Post a Comment