What do we need the BiFunction interface for?
functional-programming, java, java-8
Solution
The problem with this question is that it's not clear whether you see the purpose of a `Function`, which has a method `apply(T t)`.
The value of all the functional types is that you can pass code around like data. One common use of this is the callback, and until Java 8, we used to have to do this with anonymous class declarations:
ui.onClick(new ClickHandler() {
public void handleAction(Action action) {
// do something in response to a click, using `action`.
}
}
Now with lambdas we can do that much more tersely:
ui.onClick( action -> { /* do something with action */ });
We can also assign them to variables:
Consumer clickHandler = action -> { /* do something with action */ };
ui.onClick(clickHandler);
... and do the usual things we do with objects, like put them in collections:
Map<String,Consumer> handlers = new HashMap<>();
handlers.put("click", handleAction);
A `BiFunction` is just this with two input parameters. Let's use what we've seen so far to do something useful with `BiFunctions`:
Map<String,BiFunction<Integer,Integer,Integer>> operators = new HashMap<>();
operators.put("+", (a,b) -> a + b);
operators.put("-", (a,b) -> a - b);
operators.put("*", (a,b) -> a * b);
...
// get a, b, op from ui
ui.output(operators.get(operator).apply(a,b));
Problem
The definition of the `BiFunction` interface contains a method `apply(T t, U u)`, which accepts two arguments. However, I don't understand the use or purpose of this interface and method. What do we need this interface for?