當咱們在使用lambda去表示某個函數式接口的實例時,須要在lambda表達式的主體裏去編寫函數式接口抽象方法的實現,若是在現有的類中已經存在與抽象方法相似的方法了,咱們但願直接引用現有的方法,而不用再去從新寫實現了。方法引用讓你能夠重複使用現有的方法定義,並像Lambda同樣傳遞它們。java
方法引用和lambda表達式擁有相同的特性,它們都須要表明一個目標類型,並須要被轉化爲函數式接口的實例,不過咱們並不須要爲方法引用提供方法體,咱們能夠直接經過方法名稱引用已有方法方。方法引用要使用到操做符「::
」,左邊是類名或者對象名,右邊是方法名或者關鍵字new
數組
首先被引用方法的返回值類型要和函數式接口抽象方法的返回值類型一致,至於參數列表要根據每種引用方式而定。app
//Function<String, Long> f = x -> Long.valueOf(x); Function<String, Long> f = Long::valueOf; Long result = f.apply("10");
靜態方法引用時,靜態方法要與函數式接口抽象方法參數列表一致函數
//BiPredicate<String, String> bpredicate = (x,y) -> x.equals(y); BiPredicate<String, String> bpredicate = String::equals; boolean result = bpredicate.test("abc", "abcd"); //ToIntFunction<String> f = (s) -> s.length(); ToIntFunction<String> f = String::length; int result2 = f.applyAsInt("hello");
類型的實例方法引用時,函數式接口抽象方法的第一個參數是被引用方法的調用者,第二個參數(或者無參)是被引用方法的參數code
List<String> list = Arrays.asList("hello", "world", "aaa"); //Predicate<String> p = (s) -> list.contains(s); Predicate<String> p = list::contains; //list是lambda的一個外部對象 boolean result = p.test("aaa");
外部對象方法引用時,被引用方法與函數式接口抽象方法參數列表一致對象
//Function<Long, Date> fun = (number) -> new Date(number); Function<Long, Date> fun = Date::new; Date date = fun.apply(1000000000000L);
構造器引用時,被引用的構造方法與函數式接口抽象方法參數列表一致接口
// Function<Integer, int[]> fun = n -> new int[n]; Function<Integer, int[]> fun = int[]::new; int[] arr = fun.apply(10);
數組引用時,函數式接口抽象方法參數(數值型)即爲數組初始化大小值io