1 // lambda expressions 2 public static void DemoLambda() { 3 // 不使用lambda表达式 4 Runnable runnable1 = new Runnable() { 5 @Override 6 public void run() { 7 System.out.println("do not use lambda expressions!!"); 8 } 9 }; 10 runnable1.run(); 11 12 13 // 使用lambda表达式 14 Runnable runnable2 = () -> { 15 System.out.println("use lambda expressions!!"); 16 }; 17 runnable2.run(); 18 }
能够看到使用了lambda表达式后代码简洁了不少。lambda表达式实际就是匿名方法,他由两部分构成:参数和方法体——方法名和返回类型(经过函数体来推断)给省略了。例子中的参数为空,因此给了一个“()”表明参数为空;“->”表明使用了lambda表达式(c#中使用=>);“{}”中的内容为方法体,若是只有一句代码能够省略掉“{}”,和for循环同样。java
另外一个是函数接口。表示只有一个方法的接口就叫函数接口,能够使用注解 @FunctionalInterface 来标识这个接口是函数接口,但不是必须的。好比 Runnable 这个接口就是函数接口(只有一个方法),因此lambda表达式所实现的方法就是run方法。express
方法引用就是lambda的一种简化写法,至关于把方法当成一个变量赋值给另外一个方法,这个方法接受的参数是一个函数接口,他有3中实现:c#
1. 方法是static的:类名::方法名,例如:Math::sinapp
2. 方法不是static的:对象::方法名,例如:StringBuilder sb = new StringBuilder(); sb::appendide
3. 构造方法:类名::new函数
1 public class MethodDemo { 2 // 这个方法接受一个函数式接口 3 public static void HasFunctionalInterface(FunctionalInterfaceDemo fid) { 4 fid.doSoming("运行在:"); 5 } 6 7 // 3中实现方法 8 public static void main(String[] args) { 9 // 第一种实现:new一个匿名的对象 10 HasFunctionalInterface(new FunctionalInterfaceDemo() { 11 @Override 12 public void doSoming(String str) { 13 System.out.println(str + "之前的实现"); 14 } 15 }); 16 17 // 第二种实现:使用lambda表达式 18 // e 是参数,System.out.println("运行在:lambda表达式"); 是方法体 19 HasFunctionalInterface(e -> { System.out.println("运行在:lambda表达式"); }); 20 21 // 第三种实现:使用方法引用 22 FunctionalInterfaceImplements fif = new FunctionalInterfaceImplements(); 23 HasFunctionalInterface(fif::doSoming); 24 } 25 } 26 27 28 // 实现了函数式接口 29 class FunctionalInterfaceImplements implements FunctionalInterfaceDemo { 30 public void doSoming(String str) { 31 System.out.println(str + "方法的引用"); 32 } 33 } 34 35 36 // 一个函数式接口 37 @FunctionalInterface 38 interface FunctionalInterfaceDemo { 39 void doSoming(String str); 40 }