1 Lambda 表达式
与 C++ 以及 Python 中的差不多,总体而言类似“匿名函数”或“函数指针”;在 Java 中实际上是“匿名类的一个实例”。( params ) -> body
上例中由于只有一条语句,所以 ->
右侧可以不加花括号。
Lambda 表达式实际上是一个接口,或者接口函数。
【例】接口与 lambda 表达式
@FunctionalInterface
interface Fun { double fun( double x );}
public class LambdaIntegral
{
public static void main(String[] args) {
double d = Integral( new Fun() {
public double fun(double x) {
return Math.sin(x);
}
}, 0, Math.PI, 1e-5 );
d = Integral( x->Math.sin(x),
0, Math.PI, 1e-5 );
System.out.println( d );
d = Integral( x->x*x, 0, 1, 1e-5 );
System.out.println( d );
}
// 求积分
static double Integral(Fun f, double a, double b, double eps) {
int n,k;
double fa,fb,h,t1,p,s,x,t=0;
fa=f.fun(a);
fb=f.fun(b);
n=1;
h=b-a;
t1=h*(fa+fb)/2.0;
p=Double.MAX_VALUE;
while (p>=eps) {
s=0.0;
for (k=0;k<=n-1;k++) {
x=a+(k+0.5)*h;
s=s+f.fun(x);
}
t=(t1+h*s)/2.0;
p=Math.abs(t1-t);
t1=t;
n=n+n;
h=h/2.0;
}
return t;
}
}
【能写成 Lambda 的接口】
【例】排序
由此可见,lambda 表达式将代码当成数据来处理。这一定程度上体现了函数式编程的思想。
2 装箱与拆箱
3 枚举
由于 Java 中的枚举实际上是一个类,所以也可以拥有其他字段、方法等