deadshot
deadshot

Reputation: 9071

how to return Consumer from Function interface

I have learning functional interfaces. I have written below code to return a Consumer from Function interface but it's not working. It's returning output 0. I don't understand why it returning0.

Code:

public static void main(String[] args) {

    Function<Integer, Integer> factorial = n -> IntStream.rangeClosed(2, n)
            .reduce(1, (x, y) -> x * y);

    Function<Integer, Consumer<Integer>> f3 = n -> {
        return x -> System.out.println(factorial.apply(x * factorial.apply(n)));
    };

    f3.apply(5).accept(2); // output 0
}

Can someone explain why this is(f3.apply(5).accept(2)) returning 0. Is there any other way to implement this.

Upvotes: 2

Views: 810

Answers (2)

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

public static void main(String[] args) throws IOException {
    Function<Integer, BigInteger> factorial = n -> {
        BigInteger res = BigInteger.ONE;

        for (int i = 2; i <= n; i++)
            res = res.multiply(BigInteger.valueOf(i));

        return res;
    };

    Function<Integer, Consumer<Integer>> f3 = n -> {                // n = 5
        return (Consumer<Integer>)x -> {                            // x = 2
            BigInteger fact = factorial.apply(n);                   // 120 - correct
            fact = fact.multiply(BigInteger.valueOf(x));            // 240
            System.out.println(factorial.apply(fact.intValue()));   // too big for int and long
        };
    };

    f3.apply(5).accept(2); // 4067885363647058120493575921486885310172051259182827146069755969081486918925585104009100729728348522923820890245870098659147156051905732563147381599098459244752463027688115705371704628286326621238456543307267608612545168337779669138759451760395968217423617954330737034164596496963986817722252221059768080852489940995605579171999666916004042965293896799800598079985264195119506681577622056215044851618236292136960000000000000000000000000000000000000000000000000000000000
}

Upvotes: 3

azro
azro

Reputation: 54168

To get the Consumer in a variable, you need to split your code in 2 parts

Consumer<Integer> c = f3.apply(2);
//x -> System.out.println(factorial.apply(x * factorial.apply(5)))

c.accept(2);

From here you see that something is not gonna be find, as your consumer will do (x * 5!)! which is (120x)! so with 2 -> 240!about 10^468, where an integer can hold only up to 2^32


I'd suggest you remove a level of factorial to get easier results to understand

Function<Integer, Consumer<Integer>> f3 = n -> x -> {
    System.out.println(x * factorial.apply(n));
};

Consumer<Integer> c = f3.apply(5);

c.accept(1); // 120
c.accept(2); // 240
c.accept(3); // 360
c.accept(4); // 480

Upvotes: 1

Related Questions