我试图用Java 8编写以下代码片段-
Scanner sc = new Scanner(System.in);
System.out.println("Enter the policy amount: ");
long amount = sc.nextInt();
System.out.println("Enter the interest: ");
int interest = sc.nextInt();
System.out.println("Enter the number of years: ");
int years = sc.nextInt();
sc.close();
for (int i = 1; i <= years; i++) {
result = nextYear + amount;
calculateInterest = result * interest / 100;
nextYear = result + calculateInterest;
}
return nextYear;我需要nextYear值,因此,尝试了如下所示,使用IntStream
IntStream intStream = IntStream.rangeClosed(1, years);
intStream.forEach(num -> {
result = nextYear + amount;
calculateInterest = result * interest / 100;
nextYear = result + calculateInterest;
});但是,不确定如何返回nextYear值。如何处理这个问题,或者有没有其他方法可以做到这一点。请给我建议。谢谢。
发布于 2021-04-13 15:18:13
由于您的结果只是重复地应用循环的主体,所以通过stream获得它的方法是通过.iterate()静态方法,该方法允许您生成一个类似于一个函数的重复应用程序的流。
如果我们获取循环的主体并对其进行转换,我们就会得到:
return LongStream.iterate(0, nextYear -> {
long result = nextYear + amount;
long calculateInterest = result * interest / 100;
return result + calculateInterest;
})
.skip(years)
.findFirst()
.getAsLong();利用一些算法,我们可以简化lambda函数的体。通过内联result和calculateInterest,我们只得到一行:
nextYear -> {
return (nextYear + amount) + (nextYear + amount) * interest / 100;
}通过消除身体和通过分组重构方程,我们得到
nextYear -> ((nextYear + amount) * (100 + interest)) / 100因此,最终的跃迁如下:
return LongStream.iterate(0,
nextYear -> ((nextYear + amount) * (100 + interest)) / 100
)
.skip(years)
.findFirst()
.getAsLong();发布于 2021-04-12 16:37:18
理论上,您可能希望使用默认值为reduce的0。BinaryOperator的left将是定期更新的值,而right值仍未使用(它表示代码片段中的年份- i或num )。
double nextYear = IntStream.rangeClosed(1, years)
.mapToDouble(i -> (double) i)
.reduce(0.0, (left, right) -> left + amount + ((left + amount) * interest / 100));。。或更易读:
double nextYear = IntStream.rangeClosed(1, years)
.mapToDouble(i -> (double) i)
.reduce(0.0, (left, right) -> {
double result = left + amount;
return result + ((result) * interest / 100);
});注意:--我对nextYear、result和calculateInterest变量的类型非常困惑。您可能希望更改上面代码段上的mapToDouble或使用的类型。
备注2:然而,正如已经说过的,在Java8之前是可用的,即使在Java8之后也是可用的,所以没有理由停止使用它。
注3:,你确定计算是正确的吗?
https://stackoverflow.com/questions/67023991
复制相似问题