Lamada表达式小技巧介绍

函数式编程

@FunctionalInterface
interface Lf{
    void dispaly();
}
@FunctionalInterface为显示定义函数时编程接口,不符合函数式编程接口会报错匿名内部类使用方式
public class FunPrograming {

	public static void main(String[] args) {
		func func = new func() {
			@Override
			public void dispaly() {
				// TODO Auto-generated method stub
				System.out.println("dispaly()运行");
			}
		};
		func.dispaly();
	}
}

dispaly()运行

lamada: 拷贝小括号,写死->,落地大括号{}

public class FunPrograming {

    public static void main(String[] args) {

        func func = ()->{
            System.out.println("dispaly()运行");
        };
        func.dispaly();
    }
}
dispaly()运行
 
带返回值的接口
@FunctionalInterface
interface func {//Invalid ‘@FunctionalInterface‘ annotation; func is not a functional interface定义两个普通方法就会报错,不符合函数编程
    public void dispaly();
    public int  add(int x,int y);
}
//拷贝小括号,写死->,落地大括号{}@FunctionalInterface
interface func {
    //public void dispaly();
    public int  add(int x,int y);
}

public class FunPrograming {

    public static void main(String[] args) {
        func func = (int x,int y)->{
            System.out.println("add(int x,int y)运行");
            return x+y;
        };
        System.out.println(func.add(3,5));
    }
}

add(int x,int y)运行
8

函数式编程接口中如何定义多个方法

@FunctionalInterface
interface func {
    default void dispaly() {
        System.out.println("default void dispaly()");
    }
    default int mul(int x ,int y) {
        System.out.println("default int mul");
        return x* y;
    }
    static int dec(int x,int y) {
        System.out.println("static int dec(int x,int y)");
        return x-y;
    }
    static int div(int x,int y) {
        System.out.println("static int div(int x,int y)");
        return x/y;
    }
    public int  add(int x,int y);
}
 

相关推荐