方法引用就是經過類名或方法名引用已經存在的方法來簡化lambda表達式。那麼何時須要用方法引用呢?若是lamdba體中的內容已經有方法實現了,咱們就能夠使用方法引用。java
lamdba寫法:數組
@Test void test1(){ Consumer<String> con = x -> System.out.println(x); }
方法引用寫法:app
@Test void test2(){ PrintStream out = System.out; Consumer<String> con = out::println; }
consumer接口:ide
@FunctionalInterface public interface Consumer<T> { void accept(T t); }
注意:被調用的方法的參數列表和返回值類型須要與函數式接口中抽象方法的參數列表和返回值類型要一致。函數
lamdba寫法:this
@Test void test3(){ Comparator<Integer> com = (x, y) -> Integer.compare(x,y); }
方法引用寫法:code
@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); } }
注意:被調用的方法的參數列表和返回值類型須要與函數式接口中抽象方法的參數列表和返回值類型要一致。get
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); }
注意:第一個參數是這個實例方法的調用者,第二個參數是這個實例方法的參數時,就能夠使用這種語法。
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中的無參構造器。
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); }