A method reference to a Java 8 lambda expression:: double-colon operator

Source: Internet
Author: User

The double-colon operator is a method reference in Java, and the method references the format of the class Name:: Method name.

This is only the method name, and the method name is not followed by the parentheses "()". --------> Such a formula does not necessarily call this method. This is generally used as a lambda expression, and lambda has the so-called lazy load, not parentheses that is, to see how the method is invoked.

For example:

An expression:

Person->person.getage ();

can be replaced by

Person::getage

An expression:

(), New hashmap<> ();

can be replaced by

Hashmap::new

This method refers to or is a double-colon operation that corresponds to a parameter type of function<t,r>t that represents the passed-in type and R for the returned type. For example, the expression person--person.getage (), the passed parameter is person, the return value is Peron.getage (), then the method reference Person::getage

Corresponds to the funciton<person,integer> type.

Example code: Capitalize all the strings inside the list<string> and return to the new Arraylist<string>, as in the previous example.

@Testpublic void Converttest () {    list<string> collected = new arraylist<> ();    Collected.add ("alpha");    Collected.add ("beta");    collected = Collected.stream (). Map (String, String.touppercase ()). Collect (Collectors.tolist ());    SYSTEM.OUT.PRINTLN (collected);      }

The following form is programmed after using the double-colon operator:

@Testpublic void Testconvertest () {     list<string> collected = new arraylist<> ();     Collected.add ("alpha");     Collected.add ("beta");     collected = Collected.stream (). Map (String::touppercase). Collect (Collectors.tocollection (arraylist::new));    SYSTEM.OUT.PRINTLN (collected);     }

A method reference to a Java 8 lambda expression:: double-colon operator

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.