Java Reference
In-Depth Information
Problem
You would like to create a runnable piece of code in a terse manner.
Solution
Utilize a lambda expression to implement the
java.util.Runnable
interface. The
java.util.Runnable
interface is a perfect match for lambda expressions since it
contains only a single abstract method,
run()
. In this solution, we will compare the
legacy technique, creating a new
Runnable
, and the new technique using a lambda
expression.
The following lines of code demonstrate how to implement a new
Runnable
piece of code using the legacy technique.
Runnable oldRunnable = new Runnable() {
@Override
public void run() {
int x = 5 * 3;
System.out.println("The variable using the old
way equals: " + x);
}
};
Now take a look at how this can be written using a lambda expression instead.
Runnable lambdaRunnable = () -> {
int x = 5 * 3;
System.out.println("The variable using the lambda
equals: " + x);
};
oldRunnable.run();
lambdaRunnable.run();
As you can see, the legacy procedure for implementing a
Runnable
takes a few
more lines of code than implementing
Runnable
with a lambda expression. The