Java method reference to static method example

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

packagecom.java.lambda.methodref;importjava.util.function.BiFunction;importjava.util.function.Function;publicclassMethodReferencesDemo {publicstaticintaddition(inta,intb){return ( a+ b);    }publicstaticvoidmain(String[]args) {// 1. Method reference to a static method// lambda expressionFunction<Integer,Double> function= (input)->Math.sqrt(input);System.out.println(function.apply(4));// using method referenceFunction<Integer,Double> functionMethodRef=Math::sqrt;System.out.println(functionMethodRef.apply(4));// lambda expressionBiFunction<Integer,Integer,Integer> biFunctionLambda= (a , b)->MethodReferencesDemo.addition(a, b);System.out.println(biFunctionLambda.apply(10,20));// using method referenceBiFunction<Integer,Integer,Integer> biFunction=MethodReferencesDemo::addition;System.out.println(biFunction.apply(10,20));    }}

Output:

2.02.03030

Related Source Code Examples


Comments