Java Reference
In-Depth Information
Listing 5-4.
A LambdaUtil Class That Uses Functional Interfaces as an Argument in Methods
// LambdaUtil.java
package com.jdojo.lambda;
public class LambdaUtil {
public void testAdder(Adder adder) {
double x = 190.90;
double y = 8.50;
double sum = adder.add(x, y);
System.out.print("Using an Adder:");
System.out.println(x + " + " + y + " = " + sum);
}
public void testJoiner(Joiner joiner) {
String s1 = "Hello";
String s2 = "World";
String s3 = joiner.join(s1,s2);
System.out.print("Using a Joiner:");
System.out.println("\"" + s1 + "\" + \"" + s2 + "\" = \"" + s3 + "\"");;
}
}
The
LambdaUtil
class contains two methods:
testAdder()
and
testJoiner()
. One method takes an
Adder
as an
argument and another
Joiner
as an argument. Both methods have simple implementations. Consider the following
snippet of code:
LambdaUtil util = new LambdaUtil();
util.testAdder((x, y) -> x + y);
The first statement creates an object of the
LambdaUtil
class. The second statement calls the
testAdder()
method on the object, passing a lambda expression of
(x, y) -> x + y
. The compiler must infer the type of the
lambda expression. The target type of the lambda expression is the type
Adder
because the argument type of the
testAdder(Adder adder)
is
Adder
. The rest of the target typing process is the same as you saw in the assignment
statement before. Finally, the compiler infers that the type of the lambda expression is
Adder
.
The program in Listing 5-5 creates an object of the
LambdaUtil
class and calls the
testAdder()
and
testJoiner()
methods.
Listing 5-5.
Using Lambda Expressions as Method Arguments
// LambdaUtilTest.java
package com.jdojo.lambda;
public class LambdaUtilTest {
public static void main(String[] args) {
LambdaUtil util = new LambdaUtil();
// Call the testAdder() method
util.testAdder((x, y) -> x + y);
// Call the testJoiner() method
util.testJoiner((x, y) -> x + y);