Function
So let’s start exploring the possibilities and usages of the lambda function’s in Java. As stated before, the java.util.function packages contains functional interfaces, and in this chapter I’d like to explain how to use them.
If you look at the abstract method of the Function interface, you see It looks like this :
R apply(T t)
This method does nothing more then take an argument and returns a result. So we could write the following:
1
2
Function plus5 = (i -> i+5);
Integer var1 = plus5(1);
This function class will take an Integer, and return that integer+5. As we saw that the apply is the abstract function, i+5 is the implementation for that function. So that means that
Line 2 will set var1 to 6.
When we want more than 1 line code in the lamda function, we’ll need to use curly brackets.
1
2
3
4
5
Function plus5 = (i -> {
System.out.println(" Integer=" + i);
return i+5;
});
Integer var1 = plus5(1);
If we execute the code on the last line, it will first, print ‘5’ to the console, and then, set integer var1 to 6.
Now that we know how to use a Function, let’s have a look at another interesting method in this interface :
default Function andThen(Function after)
This is a default method, meaning that it has its implementation in the Function interface class. Using this method, we can execute multiple functions in a chain. This is well illustrated when adding a print out in the Lamda.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Function plus5 = (i -> {
System.out.println("Before plus 5 = " + i);
return i+5;
});
Function min2 = (i -> {
System.out.println("Before min2 " + i);
return i-5;
});
Function plus10 = (i -> {
System.out.println("Before plus10 " + i);
return i+10;
});
Integer var1 = plus5.andThen(min2).andThen(plus10).apply(100);
System.out.println("var1="+var1);
When executing this code, we’ll see the following output on the console :
Line 1 : before plus 5 = 100
Line 2 : before min2 105
Line 3 : before plus10 103
Line 4 : var1=113
So we execute plus5 with value 100, which prints Line 1.
andThen we execute min2 method (Line 2), entered with the new value 105 (5 added by the apply method)
andThen we execute plus10 method (Line 3), entered with the new value 103 (minus 2 by the first andThen method)
final result is 113, as 10 was added to 103 by the plus10.