新公司的代码中很多使用的 -> 这样的写法,看得我一脸懵逼,查了一下才知道这事JDK8提供的新特性,lambda表达式,在一定程度上可以简化某些代码的写法,下面我们就来一起看一下。
1.对匿名内部实现的支持:
在java中使用多线程,一般会添加一个java类实现Runable接口或者继承Thread类。也还有一种比较粗暴的方式就是创建匿名内部类,如:
//标准写法
Runnable old = new Runnable() {
@Override
public void run() {
System.out.println("this is easy to read");
}
};
Thread thread1 = new Thread(old);
thread1.start();
lambda提供了对内部类的支持,在JDK8下,下面的写法得到了和上面一样的效果:
//lambda写法
//->的写法指向的大括号中就是run方法的实现
Thread thread2 = new Thread(() -> {
System.out.println("how this could be");
});
thread2.start();
当需要实现的对象有且仅有一个抽象方法时,我们可以使用lambda表达式, -> 指向一个{},在{}中进行具体实现。
怎么样判断对象有且仅有一个抽象方法比较麻烦,JDK8还引入了另外一条新特性,函数式接口注解:@FunctionalInterface
JDK8的Runable类源码也变成了:
@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();
}
简单的就是说,Funcationallnterface注解可以添加在仅包含一个抽象方法的接口上。
JDK8的API文档中对Funcationallnterface也做了关于lambda表达式的解释:
Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
简单翻译就是有Funcationallnterface的类,支持lambda表达式进行使用。这里的Funcationallnterface更像是一个标识性注解而非功能性注解。
2.对迭代循环的支持:
现在的循环写法一般是这样的:
//通常写法
List<String> arrList = Arrays.asList("1", "2", "3", "4");
for (String str: arrList ) {
System.out.println(str);
}
引入lambda表达式后,可以写成这样:
//lambda写法
arrList.forEach(str -> {
System.out.println(str);
});
这里ArryList的forEach方法也是在JDK8的版本中新增的。