java8之后,java世界也可以使用lambda表达式了。
//lambda表达式语法
//() :参数列表
//-> :函数引用
//{} :方法体
()->{}
使用lambda时候需要定义函数式接口,函数式接口是只有一个方法的接口,并在接口名上加上@FunctionalInterface注解。在lambda表达式应用到java世界之前,实现函数式接口通常使用匿名内部类的方式实现。
匿名内部类
/**
* 函数式接口,只有一个方法
*/
@FunctionalInterface
public interface FunctionInterface {
public void test();
}
//匿名内部类
//编译后会生成独立的class文件
FunctionInterface t1=new FunctionInterface(){
public void test(){
System.out.println("匿名内部类,实现函数式接口");
}
};
t1.test();
不带参lambda
//Lambda表达式不带参数
//lambda表达式编译后不会生成独立的class文件
FunctionInterface t2=()->{
System.out.println("Lambda不带参数");
};
t2.test();
//lambda方法体只有一句话,则可省略{}
FunctionInterface t3=()->System.out.println("方法体只有一句话,可以省略{}");
t3.test();
带一个参数lambda
/**
* 函数式接口,只带一个参数
*/
@FunctionalInterface
public interface FunctionInterface1 {
public void test(int n);
}
//lambda只带一个参数
FunctionInterface1 t4=(x)->System.out.println("lambda参数:"+x);
t4.test(4);
//lambda只带一个参数,省略()
FunctionInterface1 t5=x->System.out.println("lambda待餐,省略();参数:"+x);
t5.test(5);
带多个参数lambda
/**
* 函数式接口,多个参数
*/
@FunctionalInterface
public interface FunctionInterface2 {
public void test(int n,int m);
}
//lambda表达式,待多个参数,()不可省略
FunctionInterface2 t6=(x,y)->{
int m=x+y;
System.out.println("lambda多个参数"+m);
};
t6.test(5, 9);
带返回值lambda
/**
* 函数式接口,带返回值
*
* @author lujun.chen
* @version [版本号, 2016年6月11日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
@FunctionalInterface
public interface FunctionInterface3 {
public int test(int x,int y);
}
//lambda表达式,带返回值
FunctionInterface3 t7=(x,y)->{
return x+y;
};
int m=t7.test(4, 2);
System.out.println(m);
//lambda表达式,带返回值,除了return,只有一句话,{}也可以省略
FunctionInterface3 t8=(x,y)->x+y;
int m1=t8.test(9, 2);
System.out.println(m1);