A lambda expression can access final local variables or local-non-final-initialized-only-once variables.
The following code shows that we can access and use the final local variables.
import java.util.function.Function; // w w w .j a va2 s . c o m public class Main { public static void main(String[] argv) { final String x = "Hello"; Function<String,String> func1 = y -> {return y + " "+ x ;}; System.out.println(func1.apply("java2s.com")); } }
The code above generates the following result.
The following code has a variable x which is not final but only initialized once. We can still use it in the lambda expression.
import java.util.function.Function; /* w ww. j a va 2 s .c o m*/ public class Main { public static void main(String[] argv) { String x = "Hello"; Function<String,String> func1 = y -> {return y + " "+ x ;}; System.out.println(func1.apply("java2s.com")); } }
The code above generates the following result.
The following code shows that we cannot change the value defined outside lambda expression.
import java.util.function.Function; //from ww w .ja v a2 s . c om public class Main { public static void main(String[] argv) { String x = "Hello"; Function<String,String> func1 = y -> {/*x="a";*/ return y + " "+ x ;}; System.out.println(func1.apply("java2s.com")); } }
The code above generates the following result.
We can change the non-local variable in lambda expression.
import java.util.function.Function; /* ww w . java 2 s . c o m*/ public class Main { static String x = "Hello"; public static void main(String[] argv) { Function<String,String> func1 = y -> {x="a"; return y + " "+ x ;}; System.out.println(func1.apply("java2s.com")); } }
The code above generates the following result.