Java - lambda expressions

1 - About

A lambda expression is a litteral expression that implements a functional interface (interface with only one method).

Because a functional interface contains only one abstract method, a lambda expression omit the name of the implemented method.

Usage:

  • to create instances of single-method classes more compactly
  • to pass a function as an argument to another method.
  • to treat:
    • a function function as method argument,
    • or code as data.

Sort of closure (first class function).

The lambda expression's parameter and return types are parsed, matched or adapted to a functional interface.

As a lambda expression looks a lot like a method declaration, you can consider lambda expressions as anonymous methods—methods without a name.

3 - Usage

  • You can use a lambda expression where:
  • A lambda expression can only access local variables and parameters of the enclosing block that are final or effectively final.

4 - Syntax

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses. You can omit:
    • the data type of the parameters in a lambda expression.
    • the parentheses if there is only one parameter.
  • The arrow token, →
  • A body, which consists of:
    • a single expression. The Java runtime evaluates the expression and then returns its value.

p -> p.getGender() == Person.Sex.MALE  && p.getAge() >= 18 && p.getAge() <= 25
// or
email -> System.out.println(email)

  • or a statement block. you must enclose statements in braces ({})

p -> {
    return p.getGender() == Person.Sex.MALE
        && p.getAge() >= 18
        && p.getAge() <= 25;
}

5 - Scope

Lambda expressions are lexically scoped.

They:

  • do not inherit any names from a supertype
  • or introduce a new level of scoping.

Declarations in a lambda expression are interpreted just as they are in the enclosing environment. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.

See demo

6 - Target Type

To determine the type of a lambda expression, the Java compiler uses the target type (the argument data type) of the context or situation in which the lambda expression was found.

Therefore you can only use lambda expressions only where the Java compiler can determine a target type such as

  • Variable declarations
  • Assignments
  • Return statements
  • Array initializers
  • Method or constructor arguments
  • Lambda expression bodies
  • Conditional expressions, ?:
  • Cast expressions

7 - Example

To use a lambda expression, the type of the variable need to be a functional interface. IntegerMath is a functional interface because it has only one method.


public class Calculator {
  
    interface IntegerMath {
        int operation(int a, int b);   
    }
  
    public int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }
 
    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}

8 - Backport

retrolambda - Backport of Java 8's lambda expressions to Java 7, 6 and 5

9 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap