public class LambdaTest { public static void main(String[] args) { Sum sum = (a,b)->a+b; int answer = sum.add(1,2); System.out.println(answer); } } @FunctionalInterface interface Sum{ int add(int a, int b);
> 上述代码中注意``Sum sum = (a,b)->a+b;``接口的抽象方法与这个Lambda表达式对应,并且将
方法实现为两个int型参数相加
3. 方法(Method)和构造器(Constructor)引用
Java 8 允许通过符号::来为方法和构造器添加引用
首先测试一下方法的引用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public class MethodTest { public static void main(String[] args) { Coder coder = new Coder(); Power power = coder::exchange; String answer = power.insert("HelloWorld"); System.out.println(answer); } }
class Coder { public String exchange(String s) { return s+".java"; } } @FunctionalInterface interface Power { String insert(String s); }
上列代码着重看Power power = coder::exchange;我们为coder对象的exchange方法添加了一个Power引用 当我们调用power对象引用的insert方法时,会自动执行exchange的具体实现,上述代码的运行结果为:HelloWorld.java
public class ConstructorTest { public static void main(String[] args) { PeopleFactory<People> factory = People::new; People people = factory.create("Jedrek","Wang"); System.out.println(people.toString()); } }
public class ScopeTest { public static void main(String[] args) { int num = 1; Sum sum = (a,b)->a+b; int answer = sum.add(1,num); num = 2; //这行代码不会编译 System.out.println(answer); } }