各位看官们大家好,上一回中咱们说的是Java中Lambda的例子,这一回咱们继续说该例子。闲话休提,言归正转。让我们一起Talk Android吧!
看官们,我们在前面章回中介绍了匿名函数的概念以及它的使用方法,这一回中我们重点介绍它的使用场景。
它的使用场景如下:
- 1.使用线程的时候;
- 2.使用事件监听器的时候;
- 3.集合中的接口;
- 4.自定义函数式接口;
关于第一个场景,我们举过例子。第二个种场景,我们在Andorid开发中使用比较多,最常见的就是Buttong的事件监听器。第三个场景,通常在使用集合时用的多,这里先不举例了。第四个场景属于自定义的范围,其实,我们的第一个例子就属于这种场景。只不过比较简单而已,接下来,我们介绍稍微复杂一些的例子。
下面是完成的代码:
public class Lambda {
public static void main(String[] args) {
String str1 = "This is String 1";
String str2 = "This is String 2";
int intVal1 = 1;
int intVal2 = 3;
procLambdaWith0Parmars(()->print(str1));
procLambdaWith1Parmars(str2,(s)->print(s));
procLambdaWith2Parmars(intVal1,intVal2,(a,b)->print("res: "+(a+b)));
}
public static void print(String str) {
System.out.println(str);
}
public static void procLambdaWith0Parmars(LambdaWith0Parmars p) {
p.show();
}
public static void procLambdaWith1Parmars(String str,LambdaWith1Parmars p) {
p.show(str);
}
public static void procLambdaWith2Parmars(int a,int b,LambdaWith2Parmars p) {
p.show(a,b);
}
}
interface LambdaWith0Parmars {
void show();
}
interface LambdaWith1Parmars {
void show(String str);
}
interface LambdaWith2Parmars {
void show(int a,int b);
}
下面是程序的运行结果:
This is String 1
This is String 2
res: 4
从代码中可以看出,我们主要是在第一个例子的基础上,给匿名函数添加了参数,其它的地方都没有变化。
各位看官,关于Java中Lambda的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!