简体   繁体   中英

What do we need the BiFunction interface for?

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?

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));

One of usages of BiFunction is in the Map.merge method.

Here is an example usage of the Map.merge method, which uses a BiFunction as a parameter. What merge does is basically replaces the value of the given key with the given value if the value is null or the key does not have a value. Otherwise, replace the value of the given key after applying the BiFunction .

HashMap<String, String> map = new HashMap<>();
map.put("1", null);
map.put("2", "Hello");
map.merge("1", "Hi", String::concat);
map.merge("2", "Hi", String::concat);
System.out.println(map.get("1")); // Hi
System.out.println(map.get("2")); // HelloHi

If a BiFunction were not used, you would have to write a lot more code, even spanning several lines.

Here is a link that shows all the usages of BiFunction in the JDK: https://docs.oracle.com/javase/8/docs/api/java/util/function/class-use/BiFunction.html

Go check it out!

An extra example of BiFunction is reduce() :

public static void main(String[] args) {

        List<Integer> list = new ArrayList<>(Arrays.asList(5,5,10));

        Integer reduce = list.stream().reduce(0, (v1,v2) -> v1+v2);
        System.out.println(reduce); // result is: 20

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM