Lambda表达式1
Lambda表达式用于快速重写方法
Lambda表达式语法为:(重写方法的参数) -> {重写方法的内容}
package lambda;
public class Test1 {
public static void main(String[] args) {
//如果Lambda表达式只有一条语句,可以省略大括号 (int a, int b) -> System.out.println(a + b);
A t = (int a, int b) -> {//在Lambda表达式中可以省略参数类型 (a, b) -> {}
System.out.println(a + b);
};//相当于重写了接口A中的test方法
t.test(5, 15);//调用重写的方法
}
public interface A {
public void test(int a, int b);//这个接口只能有一个方法,否则会出错
}
}
控制台输出20
如果方法只有一条返回语句,可以这么写
package lambda;
public class Test2 {
public static void main(String[] args) {
A t = (int a, int b) -> a + b;//相当于重写后的方法返回a + b
int i = t.test(5, 15);//调用重写的方法
System.out.println(i);
}
public interface A {
public int test(int a, int b);//这个接口只能有一个方法,否则会出错
}
}
控制台输出20
Lambda表达式2
Lambda表达式语法也可以为:方法的隶属者::方法名
package lambda;
public class Test3 {
public static void main(String[] args) {
A t = Test3::a;//a方法相当于重写了接口A中的test方法
t.test(5, 15);//调用重写的方法
}
public interface A {
public void test(int a, int b);//这个接口只能有一个方法,否则会出错
}
public static void a(int a, int b) {//这个方法参数必须和接口中的方法参数一致, 返回值也要一致,否则会出错
System.out.println(a + b);
}
}
控制台输出20
Lambda表达式3
Lambda表达式语法也可以为:构造方法名::new
package lambda;
public class Test4 {
public static void main(String[] args) {
A a = B::new;//相当于test方法返回一个B对象, B对象构造方法的a,b参数和接口中test方法传进去的a,b参数一致
B b = a.test(5, 15);//调用重写的方法
System.out.println(b);
}
public interface A {
public B test(int a, int b);//这个接口只能有一个方法,否则会出错
}
public static class B {
public int a;
public int b;
public B(int a, int b) {//这个构造方法参数必须和接口中的方法参数一致,否则会出错
this.a = a;
this.b = b;
}
@Override
public String toString() {
return a + b + "";
}
}
}
控制台输出20
Lambda表达式的注解
如果接口只有一个方法,可以用@FunctionalInterface注解接口,这种接口称为函数式接口
@FunctionalInterface
public interface A {
public void test(int a, int b);
}