BiFunction apply Method and Lambda Syntax
You'll learn how to write BiFunction lambdas that take two parameters and produce a result using the apply method.
Understanding BiFunction's apply Method
The BiFunction<T, U, R> interface defines a single abstract method called apply that takes two arguments of potentially different types and returns a result:
R apply(T t, U u)
This is the transformation workhorse for two-input scenarios. Think of it like a calculator that needs two numbers to produce an answer, or a recipe that requires exactly two ingredients to create a dish.
Lambda Syntax for BiFunction
Since BiFunction takes two parameters, your lambda must declare both:
BiFunction<String, Integer, String> repeater = (text, count) -> text.repeat(count);
String result = repeater.apply("Hello", 3); // "HelloHelloHello"
Notice the syntax: (param1, param2) -> expression. The parentheses around both parameters are required (unlike single-parameter interfaces where they're optional).
More Examples
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
Integer sum = add.apply(10, 5); // 15
BiFunction<String, String, Integer> compareLength = (s1, s2) -> s1.length() - s2.length();
Integer diff = compareLength.apply("Hello", "Hi"); // 3
You can also use block syntax for more complex logic:
BiFunction<Double, Double, String> maxFinder = (x, y) -> {
double max = (x > y) ? x : y;
return "Maximum: " + max;
};
Key Takeaway: BiFunction lambdas require two parameters in parentheses (param1, param2) -> result, and you invoke them using the apply(arg1, arg2) method to transform two inputs into one output.