java—如何从函数接口返回使用者

6mzjoqzu  于 2021-07-04  发布在  Java
关注(0)|答案(2)|浏览(299)

我有学习功能接口。我写了下面的代码返回一个 ConsumerFunction 接口,但它不工作。它正在返回输出 0 . 我不明白为什么它会回来 0 .
代码:

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
}

有人能解释这是为什么吗( f3.apply(5).accept(2) )返回 0 . 有没有其他方法来实现这一点。

pdtvr36n

pdtvr36n1#

为了得到 Consumer 在变量中,需要将代码分成两部分

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

c.accept(2);

从这里你会看到一些东西是找不到的,就像你的消费者会做的那样 (x * 5!)! 哪个是 (120x)! 所以用 2 -> 240! 关于 10^468 ,其中整数最多只能容纳 2^32 我建议你去掉一层 factorial 为了得到更容易理解的结果

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
vx6bjr1n

vx6bjr1n2#

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
}

相关问题