从jdk1.8开始,引入了lambda,即函数式编程。那么如和快速入门并使用这种lambda表达式呢?
为了方便函数式编程,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();
}
接口上方存在注解@FunctionalInterface,强行约束该接口是一个函数式接口(满足其特点)。
使用案例:
public class Testlambda {
public static void main(String[] args) {
//正常写法
/*Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hi!It's easy to use Lambda.");
}
})*/
//Lambda
Thread t = new Thread(() -> {
System.out.println("Hi!It's easy to use Lambda.");
});
t.start();
}
}
是不是还蛮简单的^-^