JAVA 8 method reference, java method reference

Source: Internet
Author: User

JAVA 8 method reference, java method reference
What is method reference?

Simply put, it is a Lambda expression. In Java 8, we use Lambda expressions to create anonymous methods, but sometimes Our Lambda expressions may only call an existing method without doing anything else. In this case, it is clearer to reference an existing method by using a method name. Java 8 method reference allows us to do so. Method reference is a more compact and readable Lambda expression. Note that the method reference is a Lambda expression, where the operator referenced by the method is a double colon "::".

Method reference example

Let's look at an example.

First, define a Person class as follows:

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;    }}

Suppose we have an array of persons and want to sort it. At this time, we may write as follows:

Original statement
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));    }}

The sort method of the Arrays class is defined as follows:

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

Note thatComparatorAn interface is a functional interface, so we can use Lambda expressions without defining an implementation.ComparatorInterface Class, create its instance object, and pass it to the sort method.

Using Lambda expressions, we can write as follows:

Improvement 1: Using Lambda expressions without calling existing methods
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));    }}

However, in the above Code, the comparison method for two people's birthdays has been defined in the Person class. Therefore, we can directly use the existing Person. compareByAge method.

Improvement 2: Use a Lambda expression to call an existing Method
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));    }}

Because this Lambda expression calls an existing method, we can directly use method reference to replace this Lambda expression,

3. Method reference
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));    }}

In the above Code, the method references the Person: compareByAge in terms of semantics and Lambda expressions (a, B)-> Person. compareByAge (a, B) is equivalent and has the following features:

  • The actual parameter is copied from the Comparator <Person>. compare method, that is, (Person, Person );
  • The expression body calls the Person. compareByAge method;
Four Methods reference types static method reference

In the previous example, Person: compareByAge is a static method reference.

Method reference for a specific instance object

The following example references the compareByName method of the myComparisonProvider object;

        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);
Instance method reference of any object (belonging to the same class)

The following example references the compareToIgnoreCase method of any object in the string array.

        String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" };        Arrays.sort(stringArray, String::compareToIgnoreCase);
Constructor reference

In the following example, the keyword new is used to create a set containing the Person element.

Set<Person> rosterSet = transferElements(roster, HashSet<Person>::new);
The transferElements method is defined as follows. The function is set copy,
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;}
Applicable scenarios

When a Lambda expression calls an existing Method

Which scenarios are not suitable for method reference?

It is not suitable when we need to pass other parameters to the referenced method, as shown in the following example:

IsReferable demo = () -> ReferenceDemo.commonMethod("Argument in method.");
References

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

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.