Lamada表达式小技巧介绍

Posted on   FLGB  阅读(224)  评论(0编辑  收藏  举报

函数式编程

@FunctionalInterface
interface Lf{
    void dispaly();
}
@FunctionalInterface为显示定义函数时编程接口,不符合函数式编程接口会报错
匿名内部类使用方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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();
    }
}
1
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);
}
复制代码

 

 
努力加载评论中...

Copyright © 2025 FLGB
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示