Method references are a special form of the lambda expression.
You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.
Kinds of Method References
Kind | Example |
---|---|
Reference to a static method | ContainingClass::staticMethodName |
Reference to an instance method of a particular object | containingObject::instanceMethodName |
Reference to an instance method of an arbitrary object of a particular type | ContainingType::methodName |
Reference to a constructor | ClassName::new |
1.Reference to a Static Method
Example1:
import java.util.function.Function;
public class Java8MethodReferences
{
public static void main(String[] args)
{
//Calling parseInt() method using lambda
Function<String, Integer> lambdaFunction = (String s) -> Integer.parseInt(s);
System.out.println(lambdaFunction.apply("12"));
//Calling parseInt() method using method reference
Function<String, Integer> referenceFunction = Integer::parseInt;
System.out.println(referenceFunction.apply("12"));
}
}
Example2:
import java.util.function.BiFunction;
class Multiplication{
public static int multiply(int a, int b){
return a*b;
}
}
public class Test {
public static void main(String[] args) {
//Calling multiply() method using lambda
BiFunction<Integer, Integer, Integer> lambdaProduct = (a,b) -> Multiplication.multiply(a,b);
int lp = lambdaProduct.apply(12, 5);
System.out.println("Product of given number is: "+lp);
//Calling multiply() method using method reference
BiFunction<Integer, Integer, Integer> referenceProduct = Multiplication::multiply;
int rp = referenceProduct.apply(11, 5);
System.out.println("Product of given number is: "+rp);
}
}
Example3:
package com.boraji.tutorial;
import java.util.Arrays;
import java.util.List;
/**
* @author imssbora
*/
class EvenOddChecker {
public static boolean isEven(int n) {
return n % 2 == 0;
}
}
public class MethodReferenceExample1 {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(20, 10, 15, 24, 55, 47, 16, 87, 88);
// Print even numbers using lambda expression
numbers.stream().map((n) -> EvenOddCheck.isEven(n))
.forEach((n) -> System.out.println(n));
// Print even numbers using method references
numbers.stream().map(EvenOddCheck::isEven)
.forEach(System.out::println);
}
}
2.Reference to an instance method of a particular object
Example1:
import java.util.function.Supplier;
class Company
{
String name;
public Company(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
public class Java8MethodReferences
{
public static void main(String[] args)
{
Company c = new Company("My_Company");
//Calling getName() of c using lambda
Supplier<String> lambdaSupplier = () -> c.getName();
System.out.println(lambdaSupplier.get());
//Calling getName() of c using method reference
Supplier<String> referenceSupplier = c::getName;
System.out.println(referenceSupplier.get());
}
}
Example2:
@FunctionalInterface
interface MyInterface{
void display();
}
public class Example {
public void myMethod(){
System.out.println("Instance Method");
}
public static void main(String[] args) {
//Calling myMethod() method using lambda
Example obj01 = new Example();
MyInterface ref01 = () -> obj01.myMethod();
// Calling the method of functional interface
ref01.display();
//Calling myMethod() method using method reference
Example obj02 = new Example();
MyInterface ref02 = obj02::myMethod;
// Calling the method of functional interface
ref02.display();
}
}
Example3:
package com.boraji.tutorial;
import java.util.function.BiFunction;
/**
* @author imssbora
*/
class MathOperation {
// Addition
public int add(int a, int b) {
return a + b;
}
// Subtraction
public int sub(int a, int b) {
return a + b;
}
}
public class MethodReferenceExample2 {
public static void main(String[] args) {
MathOperation op = new MathOperation();
System.out.println("--------------------Using lambda expression----------------------");
BiFunction<Integer, Integer, Integer> add1 = (a, b) -> op.add(a, b);
System.out.println("Addtion = " + add1.apply(4, 5));
BiFunction<Integer, Integer, Integer> sub1 = (a, b) -> op.sub(a, b);
System.out.println("Subtraction = " + sub1.apply(58, 5));
System.out.println("---------------------Using method reference---------------------");
BiFunction<Integer, Integer, Integer> add2 = op::add;
System.out.println("Addtion = " + add2.apply(4, 5));
BiFunction<Integer, Integer, Integer> sub2 = op::sub;
System.out.println("Subtraction = " + sub2.apply(58, 5));
}
}
3.Reference to an instance method of an arbitrary object of a particular type
Example1:
import java.util.function.Function;
public class Java8MethodReferences
{
public static void main(String[] args)
{
//Calling toLowerCase() method using lambda
Function<String, String> lambdaFunction = (String s) -> s.toLowerCase();
System.out.println(lambdaFunction.apply("JAVA"));
//Calling toLowerCase() method using method reference
Function<String, String> referenceFunction = String::toLowerCase;
System.out.println(referenceFunction.apply("JAVA"));
}
}
Example2:
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
String[] stringArray = { "Steve", "Rick", "Aditya", "Negan", "Lucy", "Sansa", "Jon"};
/* Lambda to an instance method of an arbitrary
* object of a particular type
*/
Arrays.sort(stringArray, (String a, String b) -> a.compareToIgnoreCase(b) );
for(String str: stringArray){
System.out.println(str);
}
/* Method reference to an instance method of an arbitrary
* object of a particular type
*/
Arrays.sort(stringArray, String::compareToIgnoreCase);
for(String str: stringArray){
System.out.println(str);
}
}
}
Example3:
package com.boraji.tutorial;
import java.util.ArrayList;
import java.util.List;
/**
* @author imssbora
*/
public class MethodReferenceExample3 {
public static void main(String[] args) {
List<String> weeks = new ArrayList<>();
weeks.add("Monday");
weeks.add("Tuesday");
weeks.add("Wednesday");
weeks.add("Thursday");
weeks.add("Friday");
weeks.add("Saturday");
weeks.add("Sunday");
System.out.println("--------------Using lambda expression-----------------");
weeks.stream().map((s)-> s.toUpperCase())
.forEach((s)->System.out.println(s));
System.out.println("--------------Using method reference-----------------");
weeks.stream().map(String::toUpperCase)
.forEach(System.out::println);
}
}
4. Method reference to a constructor
Example1:
package com.boraji.tutorial;
import java.util.function.BiConsumer;
/**
* @author imssbora
*/
class MathOperations {
public MathOperations(int a, int b) {
System.out.println("Sum of " + a + " and " + b + " is " + (a + b));
}
}
public class MethodReferenceExample4 {
public static void main(String[] args) {
System.out.println("------------Using lambda expression------------");
BiConsumer<Integer, Integer> addtion1 = (a, b) -> new MathOperations(a, b);
addtion1.accept(10, 20);
System.out.println("\n------------Using method reference------------");
BiConsumer<Integer, Integer> addtion2 = MathOperations::new;
addtion2.accept(50, 20);
}
}
Example2:
@FunctionalInterface
interface MyInterface{
Hello display(String say);
}
class Hello{
public Hello(String say){
System.out.print(say);
}
}
public class Example {
public static void main(String[] args) {
//Lambda to a constructor
MyInterface ref01 = (String say) -> new Hello(say);
ref01.display("Hello World!");
//Method reference to a constructor
MyInterface ref02 = Hello::new;
ref02.display("Hello World!");
}
}
参考:
《Method References》
《Java 8 Method References》
《Method References in Java 8》
《Java 8 - Method references introduction with examples》