Java 8 Lambda expressions

Let's create and run some Runnable! With Java 8, instead of using anonymous classes, we can use lambda expressions.

The syntax (params) -> statement can be used to create an instance of Runnable by implementing its run method.

This is possible only for interfaces that have only one abstract method, and such interfaces are called functional interfaces.

Wait, aren't all interface methods abstract? Starting from Java 8, that's not the case anymore. Java 8 introduced default methods, which are interface methods that have a body.

Before Java 8

Before Java 8, we had to write code like this:

Runnable r = new Runnable() {
  @Override
    public void run() {
        System.out.println("Hello!");
    }
};

r.run();
Creating a Runnable before Java 8

With Java 8 and later Java versions, we can use lambda expressions:

Runnable r = () -> System.out.println("Hello!");

r.run(); // prints "Hello!"
Creating a Runnable with Java 8

Subscribe to Java 8 Resources

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe