JDK 8 新特性 之 Lambda表达式

时间:2022-07-22
本文章向大家介绍JDK 8 新特性 之 Lambda表达式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言


  • Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。
  • Lambda 允许把函数作为参数传递进方法中。
  • 使用 Lambda 表达式可以使代码变的更加简洁紧凑。
  • lambda表达式的重要特征:
    1. 可选类型声明:不需要声明参数类型,编译器可以统一识别参数值。
    2. 可选的参数圆括号:一个参数无需定义圆括号,但多个参数需要定义圆括号。
    3. 可选的大括号:如果主体包含了一个语句,就不需要使用大括号。
    4. 可选的返回关键字:如果主体只有一个表达式返回值则编译器会自动返回值,大括号需要指定明表达式返回了一个数值。

JDK8 之前调用接口的方式是通过匿名内部类,调用接口中的方法。
@FunctionalInterface
public interface FunctionInterface {
    void get();
}

public class FunctionTest {
    public static void main(String[] args) {
        FunctionInterface functionInterface = new FunctionInterface() {
            @Override
            public void get() {
                System.out.println("get方法");
            }
        };
        functionInterface.get();
    }
}
使用Lambda表达式调用接口中的方法
@FunctionalInterface
public interface FunctionInterface {
    void get();
}

public class FunctionTest {
    public static void main(String[] args) {
        FunctionInterface ft = () -> {
            System.out.println("JDK8 Lambda表达式调用:get方法");
        };
        ft.get();
    }
}

() : 表示抽象方法所需的参数列表,(参数1,参数2) -> : 固定格式 {} :表示抽象方法的方法体

有返回值的Lambda表达式调用方法
@FunctionalInterface
public interface FunctionInterface2 {
    String get();
}
public class FunctionTest {
    public static void main(String[] args) {
        FunctionInterface2 functionInterface2 = () -> {
            return "有返回值的Lambda表达式调用方法";
        };
        System.out.println(functionInterface2.get());

        /**
         * 优化:有返回值的Lambda表达式调用方法
         */
        FunctionInterface2 functionInterface3 = () -> "优化:有返回值的Lambda表达式调用方法";
        System.out.println(functionInterface3.get());
    }
}
有参数,有返回值的Lambda表达式调用方法
@FunctionalInterface
public interface FunctionInterface3 {
    String get(String s);
}
public class FunctionTest {
    public static void main(String[] args) {
        FunctionInterface3 ft3 = (String s)-> s;
        System.out.println(ft3.get("有参数,有返回值的Lambda表达式调用方法"));
    }
}