java8 :: 双冒号传多个参数
‘::’是一种函数式接口的一种书写方法引用的方式
Kind | Syntax | Examples |
---|---|---|
Reference to a static method | ContainingClass::staticMethodName |
Person::compareByAge MethodReferencesExamples::appendStrings |
Reference to an instance method of a particular object | containingObject::instanceMethodName |
myComparisonProvider::compareByName myApp::appendStrings2 |
Reference to an instance method of an arbitrary object of a particular type | ContainingType::methodName |
String::compareToIgnoreCase String::concat |
Reference to a constructor | ClassName::new |
HashSet::new |
The following example, MethodReferencesExamples, contains examples of the first three types of method references:
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)); } }
官方文档
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html