Java 8 Lambda Expressions
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 Thread
s:
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(); } // ... }