1.概念
lambda表达式是JAVA8中提供的一种新的特性,它支持Java也能进行简单的“函数式编程”。
它是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。
2.使用
2.1首先新建函数式接口,eg Runnable。这里需要注意:函数式接口智能有一个方法
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();
}
2.2 在使用方法是,就可以把接口作为参数传进去
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
2.3 这样新建的线程的时候可以讲函数时接口作为参数
new Thread(()->{System.out.println("hello World");})
3.:: 操作符使用
class Zoo { private List animalList; public Zoo(List animalList) { this.animalList = animalList; System.out.println("Zoo created."); } } interface ZooFactory { Zoo getZoo(List animals); } class ConstructorReferenceExample { public static void main(String[] args) { //following commented line is lambda expression equivalent //ZooFactory zooFactory = (List animalList)-> {return new Zoo(animalList);}; ZooFactory zooFactory = Zoo::new; System.out.println("Ok"); Zoo zoo = zooFactory.getZoo(new ArrayList()); } }