Java 8 Lambda Expressions

From p0f
Revision as of 13:13, 7 December 2018 by Gregab (talk | contribs) (Added assumptions and intro.)
Jump to: navigation, search

Introduction

Java 8 introduced functional interfaces, a special type of an interface which only has one abstract method.

The key excerpt from the Java 8 Language Specification related to the subject of this article seems to be:

In addition to the usual process of creating an interface instance by declaring and instantiating a class (§15.9), instances of functional interfaces can be created with method reference expressions and lambda expressions (§15.13, §15.27).

What I assume

To best focus on the content of this article, I assume the reader is:

  • fluent in Java language (according to v7 language specification)

Examples

Parameterless Void Method

Consider interface Runnable, which requires you to supply a void run() method in an implementation:

public interface Runnable {
    void run();
}

This is a common way of starting Threads:

public void startThread() {
    Runnable r = new Runnable() {
        public void run() {
            new JobRunner().doJob();
        }
    };
    Thread t = new Thread(r);
    t.start();
}

Instead of going the long way, an anonymous inner class can be used in constructor parameter:

public void startThread() {
    Thread t = new Thread(new Runnable() {
        public void run() {
            new JobRunner().doJob();
        }
    });
    t.start();
}

One can now use a lambda expression to reduce the amount of boilerplate:

public class MyCode {
    // ...
    public void startThread() {
        Runnable r = () -> { new JobRunner().doJob(); };
        Thread t = new Thread(r);
        t.start();
    }
    // ...
}

Or even?

public class MyCode {
    // ...
    public void startThread() {
        Thread t = new Thread(() -> { new JobRunner().doJob(); });
        t.start();
    }
    // ...
}