Java Reference
In-Depth Information
// Call the testJoiner() method. The Joiner will
// add a space between the two strings
util.testJoiner((x, y) -> x + " " + y);
// Call the testJoiner() method. The Joiner will
// reverse the strings and join resulting strings in
// reverse order adding a comma in between
util.testJoiner((x, y) -> {
StringBuilder sbx = new StringBuilder(x);
StringBuilder sby = new StringBuilder(y);
sby.reverse().append(",").append(sbx.reverse());
return sby.toString();
});
}
}
Using an Adder:190.9 + 8.5 = 199.4
Using a Joiner:"Hello" + "World" = "HelloWorld"
Using a Joiner:"Hello" + "World" = "Hello World"
Using a Joiner:"Hello" + "World" = "dlroW,olleH"
Notice the output of the LambdaUtilTest class. The testJoiner() method was called three times, and every time
it printed a different result of joining the two strings “Hello” and “World”. This is possible because different lambda
expressions were passed to this method. At this point, you can say that you have parameterized the behavior of the
testJoiner() method. That is, how the testJoiner() method behaves depends on its parameter. Changing the
behavior of a method through its parameters is known as behavior parameterization . This is also known as passing
code as data because you pass code (logic, functionality, or behavior) encapsulated in lambda expressions to methods
as if it is data.
It is not always possible for the compiler to infer the type of a lambda expression. In some contexts, there
is no way the compiler can infer the type of a lambda expression; those contexts do not allow the use of lambda
expressions. Some contexts may allow using lambda expressions, but the use itself may be ambiguous to the compiler;
one such case is passing lambda expressions to overloaded methods.
Consider the code for the class LambdaUtil2 shown in Listing 5-6. The code for this class is the same as for the
LambdaUtil class in Listing 5-4, except that this class changed the names of the two methods to the same name of
test() , making it an overloaded method.
Listing 5-6. A LambdaUtil2 Class That Uses Functional Interfaces as an Argument in Methods
// LambdaUtil2.java
package com.jdojo.lambda;
public class LambdaUtil2 {
public void test(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);
}
 
Search WWH ::




Custom Search