1,使用函数式接口
@FunctionalInterface
public interface TestLambda8 {
void apply(String n);
}
2 测试类
public class A {
public static void main(String[] args) {
A instanceA=new A();
// Java 8之后:
List<String> features = Arrays.asList("zjq", "111");
features.forEach((n) ->A.b(n));
features.forEach((n) ->instanceA.a(n));
System.out.println();
features.forEach(instanceA::a);
features.forEach(A::b);
System.out.println();
//lambda会自动进行参数匹配
//TestLambda8这个接口只能有一个方法,下面的方法引用会匹配这个接口中的唯一方法,这就是@FunctionalInterface函数接口
TestLambda8 testLambda88=s -> System.out.println(s+7);
testLambda88.apply("testLambda88");
System.out.println();
TestLambda8 testLambda89=A::b;
testLambda89.apply("testLambda89");
System.out.println();
TestLambda8 testLambda810=instanceA::a;
testLambda810.apply("testLambda810");
x((TestLambda8)(A::b));
x((A::b));
//但是下面句代码报错
//(TestLambda8)(A::b).apply("xx");
}
public void a(String n) {
System.out.println(n+"a()");
}
public void a(String n,String s) {
System.out.println();
}
public static void b(String n) {
System.out.println(n+":b()");
}
private static void x(TestLambda8 testLambda8) {
testLambda8.apply("method x");
}
}
3 运行结果
运行结果: