JAVA 8 方法引用,java方法引用

來源:互聯網
上載者:User

JAVA 8 方法引用,java方法引用
什麼是方法引用

  簡單地說,就是一個Lambda運算式。在Java 8中,我們會使用Lambda運算式建立匿名方法,但是有時候,我們的Lambda運算式可能僅僅調用一個已存在的方法,而不做任何其它事,對於這種情況,通過一個方法名字來引用這個已存在的方法會更加清晰,Java 8的方法引用允許我們這樣做。方法引用是一個更加緊湊,易讀的Lambda運算式,注意方法引用是一個Lambda運算式,其中方法引用的操作符是雙冒號"::"。

方法引用例子

 先看一個例子

首先定義一個Person類,如下:

package methodreferences;import java.time.LocalDate;public class Person{    public Person(String name, LocalDate birthday)    {        this.name = name;        this.birthday = birthday;    }    String name;    LocalDate birthday;    public LocalDate getBirthday()    {        return birthday;    }    public static int compareByAge(Person a, Person b)    {        return a.birthday.compareTo(b.birthday);    }    @Override    public String toString()    {        return this.name;    }}

假設我們有一個Person數組,並且想對它進行排序,這時候,我們可能會這樣寫:

原始寫法
package methodreferences;import java.time.LocalDate;import java.util.Arrays;import java.util.Comparator;public class Main{    static class PersonAgeComparator implements Comparator<Person> {        public int compare(Person a, Person b) {            return a.getBirthday().compareTo(b.getBirthday());        }    }        public static void main(String[] args)    {        Person[] pArr = new Person[]{            new Person("003", LocalDate.of(2016,9,1)),            new Person("001", LocalDate.of(2016,2,1)),            new Person("002", LocalDate.of(2016,3,1)),            new Person("004", LocalDate.of(2016,12,1))};        Arrays.sort(pArr, new PersonAgeComparator());                System.out.println(Arrays.asList(pArr));    }}

其中,Arrays類的sort方法定義如下:

public static <T> void sort(T[] a, Comparator<? super T> c)

這裡,我們首先要注意Comparator介面是一個函數式介面,因此我們可以使用Lambda運算式,而不需要定義一個實現Comparator介面的類,並建立它的執行個體對象,傳給sort方法。

使用Lambda運算式,我們可以這樣寫:

改進一,使用Lambda運算式,未調用已存在的方法
package methodreferences;import java.time.LocalDate;import java.util.Arrays;public class Main{    public static void main(String[] args)    {        Person[] pArr = new Person[]{            new Person("003", LocalDate.of(2016,9,1)),            new Person("001", LocalDate.of(2016,2,1)),            new Person("002", LocalDate.of(2016,3,1)),            new Person("004", LocalDate.of(2016,12,1))};        Arrays.sort(pArr, (Person a, Person b) -> {            return a.getBirthday().compareTo(b.getBirthday());        });                System.out.println(Arrays.asList(pArr));    }}

然而,在以上代碼中,關於兩個人生日的比較方法在Person類中已經定義了,因此,我們可以直接使用已存在的Person.compareByAge方法。

改進二,使用Lambda運算式,調用已存在的方法
package methodreferences;import java.time.LocalDate;import java.util.Arrays;public class Main{    public static void main(String[] args)    {        Person[] pArr = new Person[]{            new Person("003", LocalDate.of(2016,9,1)),            new Person("001", LocalDate.of(2016,2,1)),            new Person("002", LocalDate.of(2016,3,1)),            new Person("004", LocalDate.of(2016,12,1))};        Arrays.sort(pArr, (a, b) -> Person.compareByAge(a, b));                System.out.println(Arrays.asList(pArr));    }}

因為這個Lambda運算式調用了一個已存在的方法,因此,我們可以直接使用方法引用來替代這個Lambda運算式,

改進三,使用方法引用
package methodreferences;import java.time.LocalDate;import java.util.Arrays;public class Main{    public static void main(String[] args)    {        Person[] pArr = new Person[]{            new Person("003", LocalDate.of(2016,9,1)),            new Person("001", LocalDate.of(2016,2,1)),            new Person("002", LocalDate.of(2016,3,1)),            new Person("004", LocalDate.of(2016,12,1))};        Arrays.sort(pArr, Person::compareByAge);                System.out.println(Arrays.asList(pArr));    }}

在以上代碼中,方法引用Person::compareByAge在語義上與Lambda運算式 (a, b) -> Person.compareByAge(a, b) 是等同的,都有如下特性:

  • 真實的參數是拷貝自Comparator<Person>.compare方法,即(Person, Person);
  • 運算式體調用Person.compareByAge方法;
四種方法參考型別靜態方法引用

我們前面舉的例子Person::compareByAge就是一個靜態方法引用。

特定執行個體對象的方法引用

如下樣本,引用的方法是myComparisonProvider 對象的compareByName方法;

        class ComparisonProvider        {            public int compareByName(Person a, Person b)            {                return a.getName().compareTo(b.getName());            }            public int compareByAge(Person a, Person b)            {                return a.getBirthday().compareTo(b.getBirthday());            }        }        ComparisonProvider myComparisonProvider = new ComparisonProvider();        Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
任意對象(屬於同一個類)的執行個體方法引用

如下樣本,這裡引用的是字串數組中任意一個對象的compareToIgnoreCase方法。

        String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" };        Arrays.sort(stringArray, String::compareToIgnoreCase);
構造方法引用

如下樣本,這裡使用了關鍵字new,建立了一個包含Person元素的集合。

Set<Person> rosterSet = transferElements(roster, HashSet<Person>::new);
transferElements方法的定義如下,功能為集合拷貝,
public static <T, SOURCE extends Collection<T>, DEST extends Collection<T>>    DEST transferElements(        SOURCE sourceCollection,        Supplier<DEST> collectionFactory) {                DEST result = collectionFactory.get();        for (T t : sourceCollection) {            result.add(t);        }        return result;}
什麼情境適合使用方法引用

當一個Lambda運算式調用了一個已存在的方法

什麼情境不適合使用方法引用

當我們需要往引用的方法傳其它參數的時候,不適合,如下樣本:

IsReferable demo = () -> ReferenceDemo.commonMethod("Argument in method.");
參考資料

http://java8.in/java-8-method-references/

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.