方法 引用 是可以执行一种方法的lambda表达式的简化形式。可以使用“ :: ”符号来描述。阿到特定对象的实例方法的参考指的是结合于一个非静态方法接收机。
ObjectReference::instanceMethodName
import java.util.*; public class InstanceMethodReferenceTest1 { public static void main(String[] args) { String[] stringArray = { "India", "Australia", "England", "Newzealand", "SouthAfrica", "Bangladesh", "WestIndies", "Zimbabwe" }; Arrays.sort(stringArray, String::compareToIgnoreCase); System.out.println(Arrays.toString(stringArray)); } }
输出结果
[Australia, Bangladesh, England, India, Newzealand, SouthAfrica, WestIndies, Zimbabwe]
@FunctionalInterfaceinterface Operation { public int average(int a, int b); } class MathUtility { public int getAverage(int x, int y){ return (x+y)/2; } } public class InstanceMethodReferenceTest2 { public static void main(String[] args) { MathUtility mathUtilityObject = new MathUtility(); Operation operationObject = mathUtilityObject::getAverage; int result = operationObject.average(50, 30); System.out.println("Average of two numbers: "+ result); } }
输出结果
Average of two numbers: 40