1、什么是Lambda表达式
百闻不如一见,先看一个Demo
public void tes1() throws Exception {
//用匿名内部类实现Runnable接口
Runnable r1 = new Runnable() {
public void run() {
System.out.println("Hello World");
}
};
//用Lambda实现Runnable接口
Runnable r2 = () -> System.out.println("Hello World");
}
在上面的Demo中,r2可以等同于r1
结论:使用Lambda表达式可以解决匿名内部类代码量大或者代码冗余问题,提高代码可读性。
2、使用条件
Lambda表达式需要函数式接口的支持。
简单来说,只有一个抽象方法的接口,叫作函数式接口。
例如java.lang中的只有一个抽象方法的Runnable接口,源码如下:
@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();
}
JDK 1.8之前已有的函数式接口:
java.lang.Runnable java.util.concurrent.Callable
java.security.PrivilegedAction java.util.Comparator java.io.FileFilter
java.nio.file.PathMatcher java.lang.reflect.InvocationHandler
java.beans.PropertyChangeListener java.awt.event.ActionListener
javax.swing.event.ChangeListener JDK 1.8 新增加的函数接口:
JDK 1.8 新增加的函数接口:
java.util.function
3、语法格式
格式: 左侧 -> 右侧 即(x,y,…) -> {…}
左侧:Lambda表达式的参数列表,要与函数式接口中唯一抽象方法的参数列表对应;
右侧:Lambda表达式中所要执行的代码;
左侧格式:
1、对应抽象方法为无参列表,则用”()”表示,如 () -> {…}
2、只有一个参数,可以写成(x) -> {…},或者省略括号 x -> {…}
3、一个以上的参数,(x,y,….) -> {…}
4、参数列表的数据类型可以省略不写,若要写则要写上所有参数的数据类型
右侧格式:
在“{}”中写入需要执行的代码,要注意返回值与对应抽象方法的返回值对应
如果只有一条语句要执行,”{}”可以省略不写,且可以省略”return”,如
//用Lambda实现Runnable接口
Runnable r2 = () -> System.out.println("Hello World");
上面就是Lambda的相关内容,要是总结的不好和不对,请大家指出