Java Lambda Expression Functional Interfaces

Introduction

A functional interface is an interface with only one abstract method.

Here is an example of a functional interface:

interface MyNumber {  
  double getValue();  
} 

The following code creates a lambda expression and assigns to a functional interface.

// Create a reference to a MyNumber instance.  
MyNumber myNum; 

// Use a lambda in an assignment context.  
myNum = () -> 123.45; 

The following displays the value 123.45:


System.out.println(myNum.getValue()); 
// A functional interface.  
interface MyNumber {  
  double getValue();  
}  //from  w  ww .j a v a2 s. c o  m
  
public class Main {  
  public static void main(String args[])  
  {  
    MyNumber myNum;  // declare an interface reference  
  
    myNum = () -> 123.45;  
    System.out.println("A fixed value: " + myNum.getValue());  
    // Here, a more complex expression is used.  
    myNum = () -> Math.random() * 100;  
  
    // These call the lambda expression in the previous line.  
    System.out.println("A random value: " + myNum.getValue());  
    System.out.println("Another random value: " + myNum.getValue());  
  
  }  
} 
public class Main {

   public static void main(String[] args) {
      // Invoke the lambda, passing a parameter named "text" to the
      // hello() method, returning the string
      HelloType helloLambda = (String text) -> {
         System.out.println("Hello " + text);
      };//from   w  w  w  .  j  av  a2s .  c o  m
      // Invoke the method call
      helloLambda.hello("Lambda");
   }
}

/**
 * Functional Interface
 */
interface HelloType {
   /**
    * Function that will be implemented within the lambda
    * 
    * @param text
    */
   void hello(String text);
}



PreviousNext

Related