1、如何使用 lambda表达式
1.1 构造器引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class ConstructMethodExample {
public static void main(String [] args) { Supplier<Method> supplier = Method::new; System.out.println(supplier.get()); Supplier<Method> supplier2 = () -> new Method(); System.out.println(supplier2.get());
Function<String, Method> uf = name -> new Method(name); Method method = uf.apply("一个优秀的废人"); System.out.println(method.toString()); } }
|
2、变量作用域
lambda 表达式只能引用标记了 final 的外层局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class VariableScopeTest {
public interface Converter<T1, T2> { void convert(int i); } public static void main(String [] args) {
final int num = 1; Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num)); s.convert(2); } }
|