Java8方法引用

办法援用就是通过类名或办法名援用曾经存在的办法来简化lambda表达式。那么什么时候须要用办法援用呢?如果lamdba体中的内容曾经有办法实现了,咱们就能够应用办法援用。

一、办法援用的三种语法格局

1. 对象::实例办法名

lamdba写法:

@Test
void test1(){
    Consumer<String> con = x -> System.out.println(x);
}

办法援用写法:

@Test
void test2(){
    PrintStream out = System.out;
    Consumer<String> con = out::println;
}

consumer接口:

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

留神:被调用的办法的参数列表和返回值类型须要与函数式接口中形象办法的参数列表和返回值类型要统一。

2. 类::静态方法名

lamdba写法:

@Test
void test3(){
    Comparator<Integer> com = (x, y) -> Integer.compare(x,y);
}

办法援用写法:

@Test
void test4(){
    Comparator<Integer> com = Integer::compare;
}

Comparator接口:

@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
}

Integer类局部内容:

public final class Integer extends Number implements Comparable<Integer> { 
    public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
}

留神:被调用的办法的参数列表和返回值类型须要与函数式接口中形象办法的参数列表和返回值类型要统一。

3. 类::实例办法名

lamdba写法:

@Test
void test5(){

    BiPredicate<String,String> bp = (x,y) -> x.equals(y);
}

办法援用写法:

@Test
void test6(){
    BiPredicate<String,String> bp = String::equals;
}

BiPredicate接口:

@FunctionalInterface
public interface BiPredicate<T, U> {
    boolean test(T t, U u);
}

留神:第一个参数是这个实例办法的调用者,第二个参数是这个实例办法的参数时,就能够应用这种语法。

二、结构器援用

类::new

lamdba写法:

@Test
void test7(){
    Supplier<Person> supplier = ()->new Person();
}

结构器援用写法:

@Test
void test8(){
    Supplier<Person> supplier = Person::new;
}

Supplier接口:

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

Person类:

@Data
public class Person implements Serializable {
    private static final long serialVersionUID = -7008474395345458049L;

    private String name;
    private int age;

    public Person() {
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

留神:person类中有两个结构器,要调用哪个结构器是函数式接口决定的,也就是Supplier接口中的get()办法是无参的,那么就调用的是person中的无参结构器。

三、数组援用

Type::new

lamdba写法:

@Test
void test9(){
    Function<Integer,String[]> fun = x -> new String[x];
}

数组援用写法:

@Test
void test10(){
    Function<Integer, String[]> fun = String[]::new;
}

Function接口局部内容:

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

总结

  • 办法利用及结构器援用其实能够了解为lamdba的另一种表现形式
  • 办法援用被调用的办法的参数列表和返回值类型须要与函数式接口中形象办法的参数列表和返回值类型要统一
  • 办法援用中应用类::实例办法的条件是第一个参数是这个实例办法的调用者,第二个参数是这个实例办法的参数
  • 结构器援用须要调用的结构器的参数列表要与函数式接口中形象办法的参数列表统一

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理