Channels ▼  JVM Languages  Lambda Expressions in Java 8
Variable Scope  Often, you want to be able to access variables
from an enclosing method or class in a lambda expression.
Consider this example:  public static void repeatMessage(String
text, int count) {      Runnable r = () -> {      new
Thread(r).start();  Consider a call:  repeatMessage("Hello",
1000); // Prints Hello 1,000 times in a separate thread  Now
look at the variables count and text inside the lambda
expression. Note that these variables are not defined in the
lambda expression. Instead, these are parameter variables of the
repeatMessage method.  If you think about it, something not
obvious is going on here. The code of the lambda expression may
run long after the call to repeatMessagehas returned and the
parameter variables are gone. How do the text and count
variables stay around?  To understand what is happening, we need
to refine our understanding of a lambda expression. A lambda
expression has three ingredients:    1. A block of code