Junior
What is the purpose of the BiFunction<T, U, R> functional interface in Java?
sobes.tech AI
Answer from AI
BiFunction<T, U, R> is used to represent a function that takes two arguments of types T and U, and returns a result of type R. It is a special functional interface from the java.util.function package.
Its abstract method has the following signature:
// Represents a function that takes two arguments and produces a result.
// @since 1.8
public interface BiFunction<T, U, R> {
// Applies this function to the given arguments.
// @param t the first function argument
// @param u the second function argument
// @return the function result
R apply(T t, U u);
// Returns a composed function that first applies this function to its input,
// and then applies the after function to the result.
// If evaluation of any of the expressions throws an exception, it is propagated.
// @param after the function to apply after this function
// @throws NullPointerException if after is null
// @return a composed function that first applies this function and then applies the after function
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}
Main usage scenarios:
- Aggregation and data combination: Merging or calculating a value based on two input data.
- Applying logic to two elements: Performing an operation that requires two arguments.
- Use in streams: In operations like
reduceorcollect, where elements need to be combined pairwise.
Example usage:
// Example BiFunction for adding two integers
BiFunction<Integer, Integer, Integer> sum = (a, b) -> a + b;
// Using BiFunction
int result = sum.apply(5, 3); // result will be 8
System.out.println(result);
Another example using andThen:
// Example BiFunction for adding two numbers
BiFunction<Integer, Integer, Integer> adder = (a, b) -> a + b;
// Function example for converting the sum result to a string
Function<Integer, String> toStringConverter = i -> "Result: " + i;
// Using andThen to combine BiFunction and Function
BiFunction<Integer, Integer, String> composedFunction = adder.andThen(toStringConverter);
// Applying the composite function
String finalResult = composedFunction.apply(10, 20); // finalResult will be "Result: 30"
System.out.println(finalResult);
BiFunction provides a concise and readable way to pass behavior (as a function) into methods or classes that require working with two input parameters.