Upgrading to Java 8--Chapter II Method References (method Reference)

Source: Internet
Author: User

Overview

Many Java methods use function interfaces as parameters. For example, a sort method in the Java.util.Arrays class accepts a comparator interface, which is a functional interface, and the sort method is signed as follows:

public static T[] sort(T[] array, Comparator<? super T> comparator)

Rather than passing an instance of Compartor to the sort method, pass a lambda expression.

Further, we can pass a method reference instead of a lambda expression, and a simple method reference is either a class name or an instance name followed by:: Symbol, followed by the method name.

Why do you want to use a method reference? There are two main reasons:

1. A method reference has a shorter semantics than a lambda expression because the method reference does not contain the definition as a lambda expression, and the body of the method reference has been defined elsewhere.

2. Implement code reuse.

You can use reference to static methods, instance methods, and even construct methods, using the java8 identifier "::" In the "," to make the class name/instance reference and the method name/constructor name separate, the class encapsulates the reference instance but does not implement the functional interface.

The syntax for a method reference is defined in the following ways:

ClassName::staticMethodName
ContainingType::instanceMethod
objectReference::methodName
ClassName::new

Upgrading to Java 8--Chapter II Method References (method Reference)

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.