Java 8 Lambda Expressions

From p0f
Revision as of 12:21, 21 November 2018 by Gregab (talk | contribs) (Stub example. To be finished.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Introduction

TBD.

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();
    }
    // ...
}