1. lambda表达式
格式:
(参数)->表达式
(参数)->{语句;}
示例
()->0 //无参,有返回值
()->System.out.println("lambda") //有参,有返回值
(a)->0;//有参,有返回值
(a)->System.out.println(a)//有参,无返回值
(a)->System.out::println //当只有一个参数时,调用println静态方法
(a)->{System.out.println(a);System.out.println(a);} //有参,无返回值,多个语句
(a,b)->0 //多参数,有返回值
(a,b)->System.out.println(a+b)//有参,无返回值
函数式接口
函数式接口:有仅只有一个抽象方法的接口。
我们可以看一下jdk中现有的:
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
这里我们看到线程相关的Runnable就是一个函数式接口,
而我们上面讲的lambda表达式,就是针对函数式接口的适用类型
最简单的方式,由lambda表达式表示就是下面的样子,当然这里我们什么都没做
Runnable r = ()->{};
也就是说,lambda表达式可用于函数式接口的实例化。
注:
- 当然我们的接口,有且只有一个方法时,也是可以用lambda表达式的,可以不用@FunctionalInterface这个注解
- 加上这个@FunctionalInterface注解时,编译器会检查是否只有一个方法,有多个方法时,编译器会直接报错提示