在Java 8 Stream中解决没有最终变量

有没有办法将以下代码转换为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必须是最终的或有效的最终

在此处输入图像描述

首先,更改代码以使用generics和增强的for循环。 假设valuesList ,这就是你得到的:

 List 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 ,只要它们是有效的final。

 List 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); }); 

如您所见,您没有通过使用流获得任何东西。 代码实际上更糟糕 ,所以…… 不要