gpt4 book ai didi

java - 解决Java 8 Stream里面no final variable

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:50 43 4
gpt4 key购买 nike

有没有办法将以下代码转换为 Java 8 Stream。

    final List ret = new ArrayList(values.size());
double tmp = startPrice;
for (final Iterator it = values.iterator(); it.hasNext();) {
final DiscountValue discountValue = ((DiscountValue) it.next()).apply(quantity, tmp, digits, currencyIsoCode);
tmp -= discountValue.getAppliedValue();
ret.add(discountValue);
}

Java 8 流提示没有最终变量 tmp ?有没有办法解决这种情况?

在封闭范围内定义的局部变量 tmp 必须是 final 或实际上是 final

enter image description here

最佳答案

首先,更改代码以使用泛型和增强型 for环形。假设 values然后是 List<DiscountValue> ,这就是你得到的:

List<DiscountValue> ret = new ArrayList<>(values.size());
double tmp = startPrice;
for (DiscountValue value : values) {
DiscountValue discountValue = value.apply(quantity, tmp, digits, currencyIsoCode);
tmp -= discountValue.getAppliedValue();
ret.add(discountValue);
}

我建议保留它,而不是将其转换为流,但如果您坚持,您可以使用单元素数组作为值持有者。

请注意 rettmp不必申报 final , 只要它们是有效最终的。

List<DiscountValue> ret = new ArrayList<>(values.size());
double[] tmp = { startPrice };
values.stream().forEachOrdered(v -> {
DiscountValue discountValue = v.apply(quantity, tmp[0], digits, currencyIsoCode);
tmp[0] -= discountValue.getAppliedValue();
ret.add(discountValue);
});

如您所见,使用流并没有获得任何好处。该代码实际上更糟,所以...不要

关于java - 解决Java 8 Stream里面no final variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38374961/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com