Java 方法引用

Java 方法引用

Java中使用::双冒号表示方法引用,它可以代替lambda表达式,

// lambda expression
Arrays.sort(rosterAsArray,
    (a, b) -> Person.compareByAge(a, b)
);

 

// method reference
Arrays.sort(rosterAsArray, Person::compareByAge);

以下是方法引用的种类和例子

例子

import java.util.function.BiFunction;

public class MethodReferencesExamples {
    
    public static <T> T mergeThings(T a, T b, BiFunction<T, T, T> merger) {
        return merger.apply(a, b);
    }
    
    public static String appendStrings(String a, String b) {
        return a + b;
    }
    
    public String appendStrings2(String a, String b) {
        return a + b;
    }

    public static void main(String[] args) {
        
        MethodReferencesExamples myApp = new MethodReferencesExamples();

        // Calling the method mergeThings with a lambda expression
        System.out.println(MethodReferencesExamples.
            mergeThings("Hello ", "World!", (a, b) -> a + b));
        
        // Reference to a static method
        System.out.println(MethodReferencesExamples.
            mergeThings("Hello ", "World!", MethodReferencesExamples::appendStrings));

        // Reference to an instance method of a particular object        
        System.out.println(MethodReferencesExamples.
            mergeThings("Hello ", "World!", myApp::appendStrings2));
        
        // Reference to an instance method of an arbitrary object of a
        // particular type
        System.out.println(MethodReferencesExamples.
            mergeThings("Hello ", "World!", String::concat));
    }
}

 

Oracle的文档https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注