JAVA 8 Methods Reference-Method References

Source: Internet
Author: User
Tags instance method

What is a 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 simply invoke an existing method without doing anything else, and in that case it would be clearer to refer to the existing method by a method name, Java The 8 method reference allows us to do so. The method reference is a more compact, readable lambda expression, note that the method reference is a lambda expression where the operator referred to by the method is a double colon "::".

Method Reference Example

Let's look at an example.

First define a person class, as follows:

 Packagemethodreferences;Importjava.time.LocalDate; Public classperson{ PublicPerson (String name, localdate birthday) { This. Name =name;  This. Birthday =birthday;    } String name;    Localdate birthday;  Publiclocaldate Getbirthday () {returnbirthday; }     Public Static intComparebyage (Person A, person B) {returnA.birthday.compareto (B.birthday); } @Override PublicString toString () {return  This. Name; }}

Let's say we have a person array and we want to sort it, which is what we might write:

Original wording
 Packagemethodreferences;Importjava.time.LocalDate;Importjava.util.Arrays;ImportJava.util.Comparator; Public classmain{Static classPersonagecomparatorImplementsComparator<person> {         Public intCompare (person A, person B) {returna.getbirthday (). CompareTo (B.getbirthday ()); }    }         Public Static voidMain (string[] args) {person[] pArr=Newperson[]{NewPerson ("003", Localdate.of (2016,9,1)),            NewPerson ("001", Localdate.of (2016,2,1)),            NewPerson ("002", Localdate.of (2016,3,1)),            NewPerson ("004", Localdate.of (2016,12,1))}; Arrays.sort (PARR,Newpersonagecomparator ());    System.out.println (Arrays.aslist (PARR)); }}

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

 Public Static void Super T> c)

Here, we first note that the Comparator interface is a functional interface, so we can use a lambda expression without having to define a Comparator class that implements the interface and create its instance object to pass to the sort method.

Using lambda expressions, we can write this:

improved one, using a lambda expression, without invoking an existing method
 Packagemethodreferences;Importjava.time.LocalDate;Importjava.util.Arrays; Public classmain{ Public Static voidMain (string[] args) {person[] pArr=Newperson[]{NewPerson ("003", Localdate.of (2016,9,1)),            NewPerson ("001", Localdate.of (2016,2,1)),            NewPerson ("002", Localdate.of (2016,3,1)),            NewPerson ("004", Localdate.of (2016,12,1))}; Arrays.sort (PARR, (person A, person B)- {            returna.getbirthday (). CompareTo (B.getbirthday ());                });    System.out.println (Arrays.aslist (PARR)); }}

However, in the above code, the comparison method about two birthdays is already defined in the person class, so we can use the existing Person.comparebyage method directly.

improvement Two, using a lambda expression, invoking a method that already exists
 Packagemethodreferences;Importjava.time.LocalDate;Importjava.util.Arrays; Public classmain{ Public Static voidMain (string[] args) {person[] pArr=Newperson[]{NewPerson ("003", Localdate.of (2016,9,1)),            NewPerson ("001", Localdate.of (2016,2,1)),            NewPerson ("002", Localdate.of (2016,3,1)),            NewPerson ("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 invokes an existing method, we can use the method reference directly instead of the lambda expression.

improvement Two, using method reference
 Packagemethodreferences;Importjava.time.LocalDate;Importjava.util.Arrays; Public classmain{ Public Static voidMain (string[] args) {person[] pArr=Newperson[]{NewPerson ("003", Localdate.of (2016,9,1)),            NewPerson ("001", Localdate.of (2016,2,1)),            NewPerson ("002", Localdate.of (2016,3,1)),            NewPerson ("004", Localdate.of (2016,12,1))};                Arrays.sort (PARR, person::comparebyage);    System.out.println (Arrays.aslist (PARR)); }}

In the above code, the method reference Person::comparebyage is semantically equivalent to the lambda expression (A, B), Person.comparebyage (A, B), with the following characteristics:

    • The real parameter is the copy from the Comparator<person>.compare method, i.e. (person, person);
    • The expression body calls the Person.comparebyage method;
Four methods reference type static method reference

The example that we've previously cited Person::comparebyage is a static method reference.

Method references for a specific instance object

As the following example, the referenced method is the comparebyname method of the Mycomparisonprovider object;

        classComparisonprovider { Public intComparebyname (Person A, person B) {returna.getname (). CompareTo (B.getname ()); }             Public intComparebyage (Person A, person B) {returna.getbirthday (). CompareTo (B.getbirthday ()); }} comparisonprovider Mycomparisonprovider=NewComparisonprovider (); Arrays.sort (Rosterasarray, mycomparisonprovider::comparebyname);
An instance method reference for an arbitrary object (which belongs to the same class)

As the following example, the comparetoignorecase method of any object in the string array is referenced here.

        "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" };        Arrays.sort (Stringarray, string::comparetoignorecase);
Constructing method references

The following example uses the keyword new to create a collection that contains the person element.

set<person> Rosterset = transferelements (roster, hashset<person>::new);
The Transferelements method is defined as follows, the function is a collection copy,
 Public Static extends extends collection<t>>    DEST transferelements (        SOURCE sourcecollection,        Supplier<dest > collectionfactory) {                = collectionfactory.get ();          for (t t:sourcecollection) {            result.add (t);        }         return result;}
What scenarios are appropriate for using method references

When a lambda expression invokes a method that already exists

What scenarios are not appropriate for using method references

This is not appropriate when we need to pass other parameters to the referenced method, as in the following example:

Isreferable demo = (), Referencedemo.commonmethod ("Argument in Method.");
Resources

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

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

JAVA 8 Methods Reference-Method References

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.