Sunday, 13 May 2018

Define lambda expression that accepts single value

Define a Functional interface that accepts single value.

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

/**
 * Functional interface that accepts a value.
 * 
 * @author krishna
 *
 * @param <T> The value type.
 */
public interface Consumer<T> {

 /**
  * Accepts single object.
  * 
  * @param obj
  */
 public void accept(T obj);
}

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.
  * 
  */
 public void run();
}

Application.java
package com.sample.app;

import com.sample.functional.interfaces.Consumer;
import com.sample.functional.interfaces.Task;

public class Application {

 private static void processInfo(Consumer<Task> consumer, Task task) {
  consumer.accept(task);
 }

 public static void main(String[] args) {
  Task task = new Task() {

   @Override
   public void run() {
    System.out.println("Executing the task");
   }

  };
  processInfo((myTask) -> {
   myTask.run();
  }, task);
 }
}


Output
Executing the task







Previous                                                 Next                                                 Home

No comments:

Post a Comment