BiFunction<T, U, R>: Two Inputs, One Output
What you'll learn: How to use BiFunction to create operations that accept two different arguments and produce a single result.
The Core Idea
While Function<T, R> transforms one input into an output, BiFunction<T, U, R> handles operations that need two inputs to produce a result. The three type parameters represent: T (first input type), U (second input type), and R (result type).
Think of it like a blender that needs two ingredients—fruit and liquid—to produce a smoothie. Both inputs are necessary, but they can be different types.
The apply Method
BiFunction has one abstract method: R apply(T t, U u). This method takes two arguments and returns a value.
BiFunction<String, Integer, String> repeat = (str, times) -> {
StringBuilder result = new StringBuilder();
for (int i = 0; i < times; i++) {
result.append(str);
}
return result.toString();
};
String output = repeat.apply("Hello", 3); // "HelloHelloHello"
Common Use Cases
BiFunction shines when you need to combine or compute using two distinct pieces of data:
BiFunction<Double, Double, Double> multiply = (a, b) -> a * b;
Double result = multiply.apply(5.0, 3.0); // 15.0
BiFunction<String, String, Integer> compareLength =
(s1, s2) -> s1.length() - s2.length();
Integer diff = compareLength.apply("hello", "world"); // 0
Method References
You can use method references when a method signature matches the two-input, one-output pattern:
BiFunction<Integer, Integer, Integer> max = Math::max;
Integer largest = max.apply(10, 20); // 20
Key Takeaway: BiFunction<T, U, R> extends functional programming to operations requiring two inputs, enabling more complex transformations while maintaining the clarity of the functional interface pattern.