Home > front end >  Chaining a Function with a BiFunction in Java
Chaining a Function with a BiFunction in Java

Time:10-28

I have a Function and BiFunction and I would like to chain them

Function<Integer, String> function = n -> "" n;
BiFunction<String, Boolean, List<Character>> biFunction = (str, isOK) -> Collections.EMPTY_LIST;

Is there a way to chain these two Functions such as the returned value from function is used as an input to biFunction

public List<Character> myMethod(int n, boolean isOK) {
    return function.andThen(biFunction).apply([output_of_function], isOK)
}

I couldn't find a way to provide the integer n to function nor to supply biFunction with the output of the first function.

Is it doable?

CodePudding user response:

Default methods andThen() and compose() declared in the interface Function expect another Function as an argument. It's not possible to fuse Function and BiFunction.

On the other hand method BiFunction.andThen() expects a Function as argument. But unfortunately it would be applied after BiFunction, but you need the opposite, so this option doesn't fit into your use-case.

You can combine these Function and BiFunction into a single BiFunction expecting the input of the Function function and a boolean value and producing the result generated by the by BiFunction like this:

public static <T, R, RR> BiFunction<T, Boolean, RR> getCombinedFunction(
    Function<T, R> fun, BiFunction<R, Boolean, RR> biFun
) {
    
    return (t, isOk) -> biFun.apply(fun.apply(t), isOk);
}

And use it in the following way:

Function<Integer, String> function = // initializing function
BiFunction<String, Boolean, List<Character>> biFunction =  // initializing biFunction
    
List<Character> chars = getCombinedFunction(function, biFunction).apply(12345, true);

CodePudding user response:

You can define a generic method that compose Function and BiFunction like this.

public static <A, B, C, D> BiFunction<A, C, D> compose(Function<A, B> f, BiFunction<B, C, D> bf) {
    return (a, c) -> bf.apply(f.apply(a), c);
}

And you can use like this.

Function<Integer, String> function = n -> "" n;
BiFunction<String, Boolean, List<Character>> biFunction = (str, isOK) -> Collections.emptyList();

public List<Character> myMethod(int n, boolean isOK) {
    return compose(function, biFunction).apply(n, isOK);
}

Node: You should use Collections.emptyList() instead of Collections.EMPTY_LIST. The latter gives a warning.

  •  Tags:  
  • java
  • Related