在Java 8 Stream中解决没有最终变量 [英] Solve no final variable inside Java 8 Stream

查看:1143
本文介绍了在Java 8 Stream中解决没有最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there is a way to convert the following code to 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?有办法解决这种情况吗?

Java 8 streams complains about no final variable tmp ? Is there a way to solve such situations ?

在封闭范围内定义的局部变量tmp必须是最终的或有效的最终

Local variable tmp defined in an enclosing scope must be final or effectively final

推荐答案

首先,将代码更改为使用泛型,并使用增强的更改循环。假设 List< DiscountValue> ,这就是你得到的:

First, change the code to use generics and an enhanced for loop. Assuming values is then a List<DiscountValue>, this is what you get:

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

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

I'd suggest staying with that, and not convert it to streams, but if you insist, you can use a one-element array as a value-holder.

注意 ret tmp 不必声明 final ,只要它们是有效最终的。

Note that ret and tmp doesn't have to be declared final, as long as they are effectively-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);
});

如你所见,你没有通过使用流获得任何东西。代码实际上更糟,所以......

As you can see, you haven't gained anything by using streams. The code is actually worse, so ... don't.

这篇关于在Java 8 Stream中解决没有最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆