Java - lambda expressions

Java Conceptuel Diagram

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.

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.

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;
}

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

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

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));    
    }
}

Backport

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

Documentation / Reference





Discover More
Java Conceptuel Diagram
Java - Functional Interface

in Java. A functional interface is is a interface that contains only one abstract method. The interface is so simple that java defines several standard (built-in) functional interfaces Functional...
Java Conceptuel Diagram
Java - Stream Processing

Map objects to another value as specified by a Function object Perform an action as specified by a Consumer object void forEach(Consumer action) filter, map, forEach lambda expressionsiterators...
Thread Java Mission Control
Java Concurrency - Thread

Every application has at least one thread . From the application programmer's point of view, you start with just one thread, called the main thread. From this thread, you can start other threads. ...



Share this page:
Follow us:
Task Runner