Java Lambda Expression

Java Lambda Expressions

  • Lambda expression facilitates functional programming, and simplifies the development a lot.
  • Lambda expression can only bee performed through defined functional interfaces.
  • A Java lambda expression is thus a function which can be created without belonging to any class.
  • A lambda expression can be passed around as if it was an object and executed on demand.
    Functional programming is very often used to implement event listeners as shown below:
    @FunctionalInterface  // compiler info.
    public interface StateChangeListener { 
      // called whenever the state changes
      public void onStateChange(State oldState, State newState);  
    }
    

    public class StateOwner { 
      public void addStateListener(StateChangeListener listener) { ... }
    }
    
    Before Lambda we would used an anonymous Implementation:
    StateOwner stateOwner = new StateOwner(); 
    // anonymous implementation
    stateOwner.addStateListener(new StateChangeListener() { 
      public void onStateChange(State oldState, State newState) { 
        System.out.println("State changed"); 
      } 
    });
    
    But Java lambda expression you can write the implementation like this:
    StateOwner stateOwner = new StateOwner(); 
    stateOwner.addStateListener(
    // Here is the Lambda Expession implementation
    (oldState, newState)->System.out.println("State changed")
    );
    
  • A lambda expression is characterized by the following syntax:
    parameter -> expression body
    
  • Following are the important characteristics of a lambda expression:
    1. Optional parameter type declaration − There is no need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
      (a, b) -> a - b;           // No declared type of parameters
      (int a, int b) -> a + b;   // Declared type of parameters
      
    2. Optional parenthesis around parameter − There is no need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required. For none parameters only parenthesis are required.
       // No need to declare a single parameter in parenthesis
      b -> 50 - b;        
      // For no parameters only parenthesis.       
      ( ) -> System.out.println("Zero parameter"); 
      
    3. Optional curly braces in body − There is no need to use curly braces in expression body if the body contains a single statement.
      (a, b) -> a - b;    // No need to use curly braces in the body part
      (a) -> { System.out.println("A: " + a); 
        return "return value"; }
      
    4. Optional return keyword in body − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
      (a1, a2) -> { return a1 > a2; }   // expression returns a value
      
    Here is a full Java lambda expression example:
    public class MathApp {
    
      @FunctionalInterface  // compiler info.
      interface MathOperation {
        double operation(int a, int b);
      }
    
      private double operate(int a, int b, MathOperation mathOperation) {
        return mathOperation.operation(a, b);
      }
    // Using as earlier an anonymous class implementation
      static private MathOperation add = new MathOperation() {
         @Override
        public double operation(int a, int b) {
          return a + b;
        }
      };
    // Using lambda expression with type declaration
      static private MathOperation addition = (int a, int b) -> a + b;
    
    // Using lambda expression  without type declaration
      static private MathOperation subtraction = (a, b) -> a - b;
    
    // Using lambda expression  with return statement along with curly braces
      static private MathOperation multiplication = (int a, int b) -> {
        return a * b;
      };
    
    // Using lambda expression without return statement and without curly braces
      static private MathOperation division = (int a, int b) -> (double)a / b;
      public static void main(String[] args) {
      MathApp matApp = new MathApp();
        
      System.out.println("addition   : 13 + 45 = " +add.operation(13, 45));
        
      System.out.println("addition : 14 + 5= " + matApp.operate(14,5,addition));
      System.out.println("subtr.   : 19 - 5= " + matApp.operate(19,5,subtraction));
      System.out.println("multipli.: 11 x 5= " + matApp.operate(11,5,multiplication));
      System.out.println("division : 14 / 5= " + matApp.operate(14,5,division));
      }
    }
    
    
    The result of this is:
    addition   : 13 + 45 = 58.0
    addition : 14 + 5= 19.0
    subtr.   : 19 - 5= 14.0
    multipli.: 11 x 5= 55.0
    division : 14 / 5= 2.8
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.