Java8.0新热性之Lambda表达式
2018-05-28 本文已影响0人
付凯强
0. 序言
- 代码优化的方向始终离不开简洁和易读这两个特性。
- Lambda就是为此而生。它是一种匿名方法,没有方法名,没有访问修饰符和返回值类型。
- Lambda对象的创建通过字节码指令invokedynamic来完成的,减少了类型和实例的创建消耗。而匿名类需要创建新的对象。
1. 场景
- 凡是只有一个待实现方法的接口,都可以使用Lambda。
- 以上接口通常用@FunctionalInterface来修饰。
@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. 配置
要想使用Lambda表达式,需要在app/build.gradle中添加如下配置:
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
3. 使用
- 点击事件
findViewById(R.id.main_install_apk).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "Hello Lambda");
}
});
findViewById(R.id.main_install_apk).setOnClickListener((v) -> Log.i(TAG, "Hello Lambda"));
findViewById(R.id.main_install_apk).setOnClickListener(v -> Log.i(TAG, "Hello Lambda"));
注意:当接口的待实现方法只有一个参数的时候,可以去掉参数外面的括号。
- 子线程
new Thread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "Hello Lambda");
}
}).start();
new Thread(()->Log.i(TAG, "Hello Lambda")).start();
- 接口匿名实现
LambdaListener listener_max = new LambdaListener() {
@Override
public String doSomething(String a, int b) {
String result = a + b;
return result;
}
};
LambdaListener listener_medium = (String a, int b) -> {
String result = a + b;
return result;
};
LambdaListener listener_min = (a, b) -> {
String result = a + b;
return result;
};
sayLambda((a, b) -> {
String result = a + b;
return result;
});
public void sayLambda(LambdaListener lambdaListener) {
String a = "Hello Lambda";
int b = 1024;
String result = lambdaListener.doSomething(a, b);
Log.i(TAG, "result: " + result);
}
4. 后续
如果大家喜欢这篇文章,欢迎点赞;如果想看更多前端移动端后端Java或Python方面的技术,欢迎关注!