发布于 4年前

Java 8双冒号::方法引用操作符

Java 8中,双冒号::称为方法引用操作符,我们可以使用它来引用类的方法。

::引用类的方法,返回一个函数接口(function interface),这等同于lambda表达式,但与lambda表达式不同的是,lambda表达式需要自定义一个lambda body,而::引用的是一个方法。

简单地说函数接口,就是只拥有一个抽象方法的接口,如Runnable。

::引用方法返回的函数接口不指定是什么特定的函数接口,但用于接收::方法引用返回的函数接口需要与方法有一致的签名,也就是它所接收的参数和返回值应该和方法定义的是一致的。

class MyMath{
     public double square(double num){
        return Math.pow(num , 2);
    }
}

MyMath myMath = new MyMath();
Function<Double, Double> square = myMath::square;
double ans = square.apply(23.0);

其中Function只有一个方法apply,apply接收一个参数并返回一个值。

::方法引用有以下几种用法

引用静态方法

格式:
ClassName::method

class MyMath{
    public static double square(double num){
        return Math.pow(num , 2);
    }
}

Function<Double, Double> square = MyMath::square;
double ans = square.apply(23.0);

引用实例方法

格式:
instanceRef::methName

Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("one","two","three"));
Predicate<String> pred = set::contains;
boolean exists = pred.test("one");

引用某一类型任意实例的方法

格式:
ClassName::methodName

List<User> users = new ArrayList<>();
Map<Integer, String> userMap = users.stream().collect(Collectors.toMap(User::getId,User::getName));

引用构造函数

引用构造函数ClassName::new

class Data<T>{
    T data;
}

Supplier<Data<String>> dataRef = Data<String>::new;
Data<String> Data = dataRef.get();

其中Supplier的get方法不接收参数,并返回一个值。

引用构造函数创建数组

创建数组 ClassName[]::new

©2020 edoou.com   京ICP备16001874号-3