Functions in Java
Functions in Java
Introduction
Unlike methods, functions are first-class citizens in Java. It means functions can be passed as arguments, or be returned. Here is a method in Java:
1 | public static int square(int x) { |
We can replace this method with a function:
1 | Function<Integer, Integer> square = x -> x * x; |
And we can call this function using the following code:
1 | square.apply(4);// the result is 4 * 4 = 16 |
Here’s some other simple examples:
1 | Function<Integer, Boolean> isPositive = x -> x > 0; |
Build filter using functional programming
Let’s look at a more complicate case, in this case we can implement filtering function using functional programming:
1 | import java.util.ArrayList; |
As shown in the above code, we can define different functions to filter out the results we want.
Function interface in Java
In Java, interfaces are abstract, which means we can not create an instance of an interface. For example, here is an interface:
1 | public interface I { |
If we instantiate I
using I i = new I();
, the compiler will produce an error. And if we want to have an “instance” of interface I
, we should firstly build a class which implements I
, then create an instance of this class:
1 | public class A implements I { |
However, in our previous examples(such as Function<Integer, Integer> funcition = x -> x * x;
), we instantiate a Function interface, why there is no error? What is x -> x * x
on earth?
In Java, x -> x * x
is a lambda expression. To figure out what is lambda exprssion, we can look at the following code:
1 | import java.util.function.Function; |
The output result is:
From the result we can see, function is a object LambdaDemo$$Lambda$1/303563356
, which is created by the compiler at runtime. And this object’s super class is java.lang.Object
. More importantly, this object implements the java.util.function.Function
interface, which is same as the case of interface I
and class A
. That is why we can “instantiate” a Function interface.