Method Reference

4 0 0
                                    

Method reference is used when the existing method and the lambda to be use are the same. For example:

(a, b) -> a + b;           // this is the lambda to be use

int add(int a, int b){ return a + b; } // this is the existing method

So, when instead of calling the lambda, you used a method reference pointing to the existing method. The syntax is below. It uses a double colon to call the method.

Kinds of Reference

1. Reference to a static method

     Syntax:    

     ClassName::staticMethodName

2. Reference to an instance method of a particular object

     Syntax:       

     object::instanceMethodName

3. Reference to an instance method of an arbitrary object of a particular type like String

     Syntax:

     ContainingType::instanceMethodName

4. Reference to a constructor

     Syntax:

     ClassName::new

========================

import java.util.function.BiFunction;
public class MethodReferenceDemo {
String addingString(String a, String b, BiFunction<String, String, String> bi){
return bi.apply(a, b);
}
public static void main(String[] args){
MethodReferenceDemo demo = new MethodReferenceDemo();
System.out.println(demo.addingString("Eating ", "Ham ", String::concat));
}
}

========================

Result:

Eating Ham

The BiFunction is a standard functional interface. It means that it has only one abstract method which is the apply method.

String::concat is in the rule number 3. String is the particular type. concat is the method that means concatenate or add two strings together. Since it is already an existing one, you used a method reference instead of creating another lambda invocation for the BiFunction function interface.

Java ProgrammingWhere stories live. Discover now