Lambda 无参、有参、有返回值、无返回值
public class Lambda03 {
public static void main(String
[] args
) {
LambdaInterface31 lambdaInterface31
= (String str
) -> System
.out
.println("welcome:" + str
);
lambdaInterface31
.fun("Lambda.");
LambdaInterface32 lambdaInterface32
= (String name
, int age
) -> System
.out
.println(name
+ "今年" + age
+ "岁。");
lambdaInterface32
.fun("小明", 3);
LambdaInterface33 lambdaInterface33
= (int x
, int y
) -> {
int sum
= x
+ y
;
return sum
;
};
int sum
= lambdaInterface33
.sum(2, 3);
System
.out
.println("2+3="+sum
);
LambdaInterface34 lambdaInterface34
= () ->{
System
.out
.println("无参数有返回值");
return "无参数有返回值";
};
lambdaInterface34
.fun();
}
}
interface LambdaInterface31 {
public void fun(String str
);
}
interface LambdaInterface32 {
public void fun(String name
, int age
);
}
interface LambdaInterface33 {
public int sum(int x
, int y
);
}
interface LambdaInterface34 {
public String
fun();
}
输出结果:
welcome:Lambda.
小明今年3岁。
2+3=5
无参数有返回值
函数一个参数或实现的函数体只有一行代码时函数可以简写
LambdaInterface31 lambdaInterface31
= (String str
) -> System
.out
.println("welcome:" + str
);
lambdaInterface31
.fun("Lambda.");
LambdaInterface31 lambdaInterface311
= (str
) -> System
.out
.println("welcome:" + str
);
lambdaInterface311
.fun("Lambda311.");
LambdaInterface31 lambdaInterface312
= str
-> System
.out
.println("welcome:" + str
);
lambdaInterface312
.fun("Lambda312.");
输出结果:
welcome:Lambda.
welcome:Lambda311.
welcome:Lambda312.