DEV Community

loading...

Java 8 lambdas: 101

shriyog profile image Shriyog Ingale ・2 min read

All you need is 5 minutes to grok the Lambda expressions introduced in Java 8. This post acts as a starter by quickly demonstrating how lambdas are super cool in replacing hefty anonymous classes.

Anonymous classes

You have used them all over - to implement event handlers in GUIs, to specify a Comparator for sorting, etc.

    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World!");
        }
    });

By doing this, we are just passing the functionality of handling an event. As in passing code as a method argument.

The problem with simplest anonymous classes - one with a single abstract method, is the unnecessary boiler-plate syntax going along with it.

Lambdas exactly solve this by providing a clean & compact syntax to convey the functionality of single method classes.

A minimalistic example

  • An interface - Operation
  • A class - Calculator

The Operation interface declares a method to operate on 2 integers. This can be implemented by multiple types of operations such as Addition and Subtraction.

public interface Operation {
    int operate(int a, int b);
}

The static calculate method performs the operation by calling operate method using supplied operands.

public class Calculator {
    public static int calculate(int a, int b, Operation operation) {
        return operation.operate(a, b);
    }
}

We want to invoke calculate to perform a defined operation(implementation of Operation interface) on given operands.

Approach 1 - Using Anonymous class

    Operation additionOperation = new Operation() {
        @Override
        public int operate(int a, int b) {
            return a + b;
        }
    };

    int result = Calculator.calculate(2, 3, additionOperation);

Approach 2 - Using lambda expression

    int result = Calculator.calculate(2, 3, (x, y) -> x + y);

The lambda expression (x, y) -> x + y can be dissected into

  1. (x, y)
    Parenthesis enclosed comma separated set of formal arguments(same as in the Interface method signature).

  2. ->
    The arrow to differentiate.

  3. x + y
    The body which can have an expression which is evaluated and returned or a block of statements enclosed by curly braces.

This is how lambdas can easily replace those bulky anonymous classes. They also seem to fit perfectly with the new Java stream API which is a collection of functional-style transformations.

Resources

Oracle Java tutorials - Lambda expressions

Discussion (0)

Forem Open with the Forem app