Java Learning Notes-method references

Source: Internet
Author: User

Method Reference (Methods Reference)

A lambda expression was recorded in the previous article, which can create an anonymous method. when a lambda expression simply calls an existing method, you can take a method reference (the attribute that JDK8 has). As follows:

1  Public classPerson {2 3      Public enumSex {4 MALE, FEMALE5     }6 7 String name;8 localdate birthday;9 Sex gender;Ten String EmailAddress; One     intAge ; A  -      Public intGetage () { -         returnAge ; the     } -      -      Publiclocaldate Getbirthday () { -         returnbirthday; +     }     -  +      Public Static intComparebyage (Person A, person B) { A         returnA.birthday.compareto (b.birthday); at     } -}

Suppose you need to sort a group of people by age, you can pass the people array to the Array.Sort method in the following way, with the implemented comparer:

1person[] Rosterasarray = Roster.toarray (Newperson[roster.size ()]);2 3 classPersonagecomparatorImplementsComparator<person> {4      Public intCompare (person A, person B) {5         returna.getbirthday (). CompareTo (B.getbirthday ());6     }7 }8         9Arrays.sort (Rosterasarray,NewPersonagecomparator ());

Of course, you can use the Personagecomparator implementation as a lambda expression, as follows:

1  Arrays.sort (Rosterasarray, (A, B), A.birthday.compareto (B.birthday));

The person class already contains a comparison comparebyage based on age, which only needs to be called directly in the lambda expression body :

1 (A, B), Person.comparebyage (A, b));

Because a lambda expression invokes a method that already exists, you can use a method reference instead of a lambda expression, as follows:

1 person::comparebyage);

Among them, Person::comparebyage and (A, B), Person.comparebyage (A, b) are equivalent. (1) Its parameters are copied in Comparator<person>.compare, i.e.(Person, Person);(2)body将调用Person.compareByAge。

Method Reference Category

There are 4 methods to refer to, as follows:

    • Referencing static methods, such as Containingclass::staticmethodname;
    • Referencing instance methods, such as Containingobject::instancemethodname;
    • Methods that refer to special types of objects, such as Containingtype::methodname;
    • Reference constructors, such as Classname::new.
(1) referencing static methods

The example above is a static method reference.

(2) Reference instance method

That is, the method is referenced by an instance of the class, as follows:

1 classComparisonprovider {2      Public intComparebyname (Person A, person B) {3         returna.getname (). CompareTo (B.getname ());4     }5         6      Public intComparebyage (Person A, person B) {7         returna.getbirthday (). CompareTo (B.getbirthday ());8     }9 }TenComparisonprovider Mycomparisonprovider =NewComparisonprovider (); OneArrays.sort (Rosterasarray, mycomparisonprovider::comparebyname);
(3) Methods for referencing special types of objects

Take string for example:

1 string[] Stringarray = {"Barbara", "James", "Mary", "John",2     "Patricia", "Robert", " Michael "," Linda " }; 3 arrays.sort (Stringarray, string::comparetoignorecase);
(4) Reference constructor

Suppose transferelements implements a copy element from one collection to another, as follows:

1  Public Static<t, SOURCEextendsCollection<t>, DESTextendsCollection<t>>2 DEST transferelements (3 SOURCE sourcecollection,4Supplier<dest>collectionfactory) {5         6DEST result =collectionfactory.get ();7          for(T t:sourcecollection) {8 Result.add (t);9         }Ten         returnresult; One}

Where supplier contains a GET method that returns only an empty collection object, and does not require any parameters, it can be implemented using a lambda expression, as follows:

1 set<person> rostersetlambda =2     returnnew hashset<> ();});

You can take the method of referencing the constructor at this point, as follows:

set<person> Rosterset = transferelements (Roster, HashSet::new); // or set<person> Rosterset = transferelements (roster, hashset<person>::new);
Summarize
    • In the case of lambda expressions, when just invoking an existing method, it can be implemented by means of a method reference, which the compiler will translate itself
Reference

Method references

Java Learning Notes-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.