什么时候可以使用lambda?
1.简化匿名内部类
代码语言:javascript
复制Lambda可以简化的内容:
1.lambda中如果只有一条语句,可以把{}省略掉,如果有返回值return也省略掉
2.参数列表中的类型是可以推断出来的,所以可以省略
3.方法引用简化: Comparator<String> comparator = String::comparaTo;
2.代码
代码语言:javascript
复制package d01_lamda;
import java.util.Comparator;
/**
* zt
* 2020/8/13
* 9:42
* Lambda
*
*/
public class Demo1 {
public static void main(String[] args) {
//1.匿名内部类
Runnable run1 = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() "执行了");
}
};
run1.run();
//优化匿名内部类
Runnable run2 = ()-> System.out.println(Thread.currentThread().getName() "执行了");
run2.run();
//2.匿名内部类
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
};
System.out.println(comparator.compare("sad", "asfgasfg"));
//优化
Comparator<String> comparator2 = (String o1, String o2)-> {
return o1.compareTo(o2);
};
//优化
Comparator<String> comparator3 = (o1, o2)-> o1.compareTo(o2);
Comparator<String> comparator4 = String::compareTo;
}
}
3.运行结果
代码语言:javascript
复制main执行了
main执行了
18
Process finished with exit code 0