Static Method References
Description
A static method reference allows us to use a static method as a lambda expression.
The static methods can be defined in a class, an interface, or an enum.
Example
The following code defines two lambda expressions.
The first lambda expression func1
is created by defining
an input parameter x and providing
lambda expression body. Basically it is the normal way of creating a lambda expression.
The second lambda expression func2
is created by referening a static method
from Integer
class.
import java.util.function.Function;
/*from ww w.j a v a2 s .c om*/
public class Main {
public static void main(String[] argv) {
// Using a lambda expression
Function<Integer, String> func1 = x -> Integer.toBinaryString(x);
System.out.println(func1.apply(10));
// Using a method reference
Function<Integer, String> func2 = Integer::toBinaryString;
System.out.println(func2.apply(10));
}
}
The signature of the static method from the Integer class is as follows.
static String toBinaryString(int i)
The code above generates the following result.
Example 2
The following code shows how to use the Integer.sum as lambda expression.
import java.util.function.BiFunction;
/*ww w .j a va 2s. c o m*/
public class Main {
public static void main(String[] argv) {
// Uses a lambda expression
BiFunction<Integer, Integer, Integer> func1 = (x, y) -> Integer.sum(x, y);
System.out.println(func1.apply(2, 3));
// Uses a method reference
BiFunction<Integer, Integer, Integer> func2 = Integer::sum;
System.out.println(func2.apply(2, 3));
}
}
The code above generates the following result.