【Java8新特性】- Lambda表达式( 二 )


MathService math = new MathService() {    @Override    public Integer add(int a, int b) {        return a + b;    }};MathService mathService = (a, b) -> a + b;System.out.println(mathService.add(1, 1));方法引入规则方法引入需要遵循规范:方法参数列表、返回类型与函数接口参数列表与返回类型必须要保持一致 。方法引入的规则:       静态方法引入: 类名::(静态)方法名称       对象方法引入: 类名:: 实例方法名称       实例方法引入:new对象 对象实例::方法引入       构造函数引入:类名::new方法引用提供了非常有用的语法,可以直接引用已有的java类或对象的方法或构造器 。方法引用其实也离不开Lambda表达式 , 与lambda联合使用,方法引用可以使语言的构造更加紧凑简洁,减少冗余代码 。方法引用提供非常有用的语法,可以直接引用已有的java类或者对象中方法或者构造函数 , 方法引用需要配合Lambda表达式语法一起使用减少代码的冗余性问题 。

【Java8新特性】- Lambda表达式

文章插图
实例构造器引用通过构造器引用实例化对象,
public static void main(String[] args) {    // 使用匿名内部类    CarService carService = new CarService() {        @Override        public Car getCar() {            return null;        }    };    // 使用引用方法    CarService car = Car::new;    car.getCar();}public class Car {    private String name;    private String brand;    public Car() {    }}public interface CarService {    Car getCar();}静态方法引入UserService u = UserService::hello;u.get();在userservice中 , 有一个抽象get方法和一个静态方法
@FunctionalInterfacepublic interface UserService {    void get();    static void hello() {        System.out.println("hello");    }}运行后会输出hello
helloProcess finished with exit code 0对象方法引入这是一种更为方便的写法, 我记得在mybatis-plus使用自带条件查询的时候会用到这种方式,以下用简单例子来实现 。java8中提供了public interface Function<T, R>的类,这个类也是使用@FunctionalInterface注解 , 可见也是函数式接口 。代码:
// 在car中声明一个方法public class Car {    public String Info() {        return "保时捷 - 帕拉梅拉";    }}// 函数式接口@FunctionalInterfacepublic interface CarInFoService {    String getCar(Car car);}测试采用了三种方式进行比较
public class LambdaTest4 {    public static void main(String[] args) {        System.out.println("**************匿名内部类**************");        CarInFoService carInFoService = new CarInFoService() {            @Override            public String getCar(Car car) {                return car.Info();            }        };        System.out.println(carInFoService.getCar(new Car()));        System.out.println("**************lambda**************");        CarInFoService carInFoService2 = (car) -> car.Info();        System.out.println(carInFoService2.getCar(new Car()));        System.out.println("**************对象方法引入**************");        CarInFoService carInFoService3 = Car::Info;        System.out.println(carInFoService3.getCar(new Car()));        // R apply(T t); T  apply方法传递的参数类型 : R apply 方法返回的类型        Function<String, Integer> function = String::length;        System.out.println(function.apply("lyd_code"));    }}

推荐阅读