This source code example demonstrates the usage of the Java method reference to the static method.
Well, a Java method reference to static method is a type of method reference introduced in Java 8.
Method reference is used to refer method of the functional interface. It is a compact and easy form of a lambda expression.
You can refer to the static method defined in the class. Following is the syntax and example which describe the process of referring to the static method in Java.
Syntax :
ContainingClass::staticMethodName
Java method reference to static method example
package com.java.lambda.methodref;
import java.util.function.BiFunction;
import java.util.function.Function;
public class MethodReferencesDemo {
public static int addition(int a, int b){
return ( a + b);
}
public static void main(String[] args) {
// 1. Method reference to a static method
// lambda expression
Function<Integer, Double> function = (input) -> Math.sqrt(input);
System.out.println(function.apply(4));
// using method reference
Function<Integer, Double> functionMethodRef = Math::sqrt;
System.out.println(functionMethodRef.apply(4));
// lambda expression
BiFunction<Integer, Integer, Integer> biFunctionLambda = (a , b) -> MethodReferencesDemo.addition(a, b);
System.out.println(biFunctionLambda.apply(10, 20));
// using method reference
BiFunction<Integer, Integer, Integer> biFunction = MethodReferencesDemo::addition;
System.out.println(biFunction.apply(10, 20));
}
}
Output:
2.0
2.0
30
30
Comments
Post a Comment