如何从Function接口返回Consumer



我有学习功能接口。我已经写了下面的代码来从Function接口返回Consumer,但它不起作用。它正在返回输出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吗。还有其他方法可以实现这一点吗。

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
}

要获得变量中的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

最新更新