1 Lambda 表示式的形式
根据方法参数个数的不同、方法体内语句数量的不同,Lambda 表达式的形式呈现多种多样。
package com.hcong.functional;
/**
* @Classname LambdaExpressions
* @Date 2023/4/7 16:59
* @Created by HCong
*/
interface Description {
String brief();
}
interface Body {
String detailed(String head);
}
interface Multi {
String twoArg(String head, Double d);
}
public class LambdaExpressions {
static Description desc = () -> "Short info"; // [1]
static Body bod1 = h -> h + " No parens!"; // [2]
static Body bod2 = h -> h + " More details"; // [3]
static Multi mult = (h, n) -> h + n; // [4]
static Description moreLines = () -> { // [5]
System.out.println("moreLines()");
return "from moreLines()";
};
public static void main(String[] args) {
System.out.println(desc.brief());
System.out.println(bod1.detailed("Oh!"));
System.out.println(bod2.detailed("Hi!"));
System.out.println(mult.twoArg("Pi! ", 3.14159));
System.out.println(moreLines.brief());
}
}
Short info
Oh! No parens!
Hi! More details
Pi! 3.14159
moreLines()
from moreLines()
2 Lambda 表达式与递归
若需要将递归方法编写成 Lambda 表达式的形式,那么递归方法必须是实例变量或静态变量。
package com.hcong.functional;
/**
* @Classname RecursiveFactorial
* @Date 2023/4/7 17:07
* @Created by HCong
*/
interface IntCall {
int call(int arg);
}
public class RecursiveFactorial {
static IntCall fact;
public static void main(String[] args) {
fact = n -> n == 0 ? 1 : n * fact.call(n - 1);
for (int i = 0; i <= 10; i++) System.out.println(fact.call(i));
}
}
1
1
2
6
24
120
720
5040
40320
362880
3628800