Lambas in Java 8

Another new feature in Java 8 is the lambda construct. Unlike the properties which are an addition to the standard library, lambdas are a language feature. They allow you to define a single function without needing a complete class to go with it.

Old way

If you want to handle the click event of a Swing based button you would add an anonymous class:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Clicked!");
    }
});

New with lambda

button.addActionListener((e) -> System.out.println("Clicked!"))

As you can see the code lost much of boiler plate code by using the lambda. We keep the reference to the ActionEvent parameter called e - even we don't use it.

Lambda Syntax

Lambdas always follow this form:

(parameters) -> <code>

Where code can be a single instruction (omitting the closing semicolon) or a block of code denoted by { and }:

(p1, p2, p3) -> {
    int result = p2 * p3;
    return result + p1;
}

When using the short form there is an implicit return at the start of that line, so you can omit that, too.

Lambda as a Type

You might ask yourself now how to define a function that takes another function as a parameter. If you want to create a function that can be called for example like this:

myFunction(() -> 1+1);

Java does not provide a function type for you to use. What you do use is the type of an interface that only has a single public method. There is no interface that you have to use for this - you can just define one yourself if you like:

@FunctionalInterface
public interface FunctionType {

    public int giveMeAnInt();

}

We use the @FunctionalInterface annotation here but this is completely optional. All it does is warn you when the interface definition does not fit the requirements to be used as a lambda type.

Your function definition would then be this:

public void myFunction(FunctionType a) {
    System.out.println(a.giveMeAnInt());
}

But Java provides some predefined interfaces you can use in the package java.util.function. Among them:

  • Function takes a parameter of type and returns an object of type R.
  • Predicate takes a parameter of type T and returns a boolean.
  • Supplier has no parameter and returns an object of type T.

There is no interface for the case that you need a function that takes no parameters and returns nothing - in this case it is recommended that you just use Runnable as the type.

Static Methods

EDIT ME

You can also use a static function where a lambda is expected by using the :: symbol:

public class StaticLambdaClass {

    public static int getThatInt() {
        return 5;
    }

    public static void main() {
        myFunction(StaticLambdaClass::getThatInt);
    }