Rishabh Jain
Rishabh Jain

Reputation: 123

Chaining of function and bifunction in java 8

Java-8 comes with Function and BiFunction. How we can chain multiple Function or Bifunction instances. So that output of one become input of another Function. I've created simple functions and Bifunctions to illustrate.

import java.util.function.BiFunction;
import java.util.function.Function;

class FunctionSample1 {

    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> mul = (x, y) -> {
            return x * y;
        };

        BiFunction<Integer, Integer, Integer> div = (x, y) -> {
            return x / y;
        };

        BiFunction<Integer, Integer, Integer> sum = (x, y) -> {
            return x + y;
        };

        BiFunction<Integer, Integer, Integer> sub = (x, y) -> {
            return x - y;
        };

        Function<Integer, Integer> mulfunc = (y) -> {
            return y * 9;
        };

        Function<Integer, Integer> divfunc = (y) -> {
            return y / 2;
        };

        Function<Integer, Integer> sumfunc = (y) -> {
            return y + 89;
        };

        Function<Integer, Integer> subdunc = (y) -> {
            return y - 2;
        };
    }
}

How can I chain them whether using compose or andThen for getting the result ?

Upvotes: 1

Views: 1931

Answers (2)

Andrew
Andrew

Reputation: 49606

Both Function and BiFunction have a method andThen(Function) to let you build composed functions.

BiFunction.andThen(Function) = BiFunction
Function.andThen(Function) = Function

For example,

BiFunction<Integer, Integer, Integer> mul = (x, y) -> x * y;
Function<Integer, Integer> times2 = x -> x * 2;
Function<Integer, Integer> minus1 = x -> x - 1;

// r = ((3 * 3) * 2) - 1
Integer r = mul.andThen(times2).andThen(minus1).apply(3, 3);

Function also has a method compose(Function).

Function1.compose(Function0) = Function0.andThen(Function1) = Function

For example,

// r2 = (3 - 1) * 2
Integer r2 = times2.compose(minus1).apply(3);

Upvotes: 10

Rishabh Jain
Rishabh Jain

Reputation: 123

int k = mulfunc.andThen(divfunc).andThen(sumfunc).andThen(subdunc).apply(6);
System.out.println(k);

Upvotes: 0

Related Questions