函数式接口:有且仅有一个抽象方法的接口

格式:

修饰符 interface 接口名称 {
    public abstract...
    //
    其他非抽象方法
}

image.png

@FunctionalInterface
注解作用:检测接口是否是一个函数式接口

使用:一般作为方法的参数和返回值类型
image.png
image.png

匿名内部类依旧会产生.class文件,但是Lambda表达式并不会(可以节省空间)

函数式编程

Lambda的延迟执行

Lambda适应前提必须存在函数式接口

有些场景代码执行后,他的结果却用不上,从而造成性能浪费,但Lambda是延迟执行的,可以作为解决方案,提升性能

日志案例

    public static void showLog(int level, String message) {
        if (level == 1) {
            System.out.println(message);
        }
    }

    public static void main(String[] args) {
        String msg1 = "hello ";
        String msg2 = "world ";
        String msg3 = "java";

        showLog(1, msg1 + msg2 + msg3);
    }

如果level != 1, 那么字符串拼接就白费了

优化
    public static void showLog(int level, MyFunctional mb) {
        if (level == 1) {
            System.out.println(mb.buildMessage());
        }
    }

    public static void main(String[] args) {
        String msg1 = "hello ";
        String msg2 = "world ";
        String msg3 = "java";

        showLog(1, () -> {
            return msg1 + msg2 + msg3;
        });
        
        //简化
        showLog(1, () -> msg1 + msg2 + msg3);
    }

image.png

函数式作为参数案例

image.png

image.png
方法的参数必须是函数式接口才能这样使用

函数式作为返回值案例

image.png
image.png

image.png


waikiki
4 声望2 粉丝