Sage-Code Laboratory
index<--

Lambda Expressions

Lambda expressions are new in Java. This feature makes the language slick and helps to simplify code. It is used mostly to create dynamic algorithms in core packages.

A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name. Whereas, Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time.

A lambda expression is simple to grasp. It consist of a list of arguments, follow by arrow symbol "->" follow by an aritmetic expression or other kind of expression that can produce a result.

Syntax


(arguments) -> expression

Alternative


(arguments) -> { 
    return expression
}

Example

Functional interfaces, can be implemented by a Lambda Expression. A Java lambda expression implements a single method from a Java interface.

A labda expression looks nice, but using it require some skills. You can read the example below and convince yourself. In this example we use two lamda expressions as call-back functions.

public class Calculator {
  
    // define a functional interface
    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;

        // call using lamda expression as argument
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));

        // call using lamda expression as argument    
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}

Output


>java -classpath .:target/dependency/* Calculator
40 + 2 = 42
20 - 10 = 10

External references:


Read next: Regular Expressions