java8 two new features - a reference method

Java 8 reference method

introduction

After learning of lambda expressions, we often use the method to create an anonymous lambda expression. However, sometimes we just call a method that already exists. as follows:

Arrays.sort(stringsArray,(s1,s2)->s1.compareToIgnoreCase(s2));

 In Java8, we can be referenced directly by means of a shorthand method lambda expression that already exist.

Arrays.sort(stringsArray, String::compareToIgnoreCase);

 

Introduction

This feature is called a reference method (Method Reference).

The method referred to by the name of the method to point to a method.

The method reference can be made more compact and simple construction of the language, to reduce redundant code.

Method references a pair of colons  :: 

 

 

Reference types

The method is referenced standard form: 类名::方法名. ( Note: only need to write the method name, no need to write parentheses )

There are four types of method references, use the most should be the third:

Types of Examples
Reference a static method ContainingClass::staticMethodName
An object reference to an instance method containingObject::instanceMethodName
Examples of the method of any reference to a type of object ContainingType::methodName
Reference constructor ClassName::new

 

 

 

 

 

 

Case (comparison using lambda)

package jdk8.lambda;

import java.time.LocalDate;
import java.util.Arrays;

/**
 * jdk8.lambda
 *
 * @Description:
 * @author: changliu
 * @Date: 2019/7/31
 */
public class refer {
    /**
     * 实体类-人
     */
    public static class Person{
        public Person(String name, LocalDate birthday) {
            this.name = name;
            this.birthday = birthday;
        }
        private String name;
        private LocalDate birthday;
        
        public static int compareByAge(Person a, Person b) {
            return a.birthday.compareTo(b.birthday);
        }
    }

    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))};
        
        // Use the static method and the type of the lambda expression 
        Arrays.sort (Parr, (A, B) -> Person.compareByAge (A, B)); 

        // use method references, references are static class 
        Arrays.sort (Parr, the Person :: compareByAge);
 
        System.out.println (Arrays.asList (Parr)); 
    } 
}

The case highlighted in red is the use of a reference method can be seen more concise.

 

Guess you like

Origin www.cnblogs.com/wish5714/p/11277619.html