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

时间:2016-07-14 13:00:44

标签: java java-8 java-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必须是最终的或有效的最终

enter image description here

2 个答案:

答案 0 :(得分:6)

首先,更改代码以使用泛型和增强的for循环。假设valuesList<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);
});

正如您所看到的,您通过使用流而无法获得任何收益。代码实际上更糟,所以...... 不要

答案 1 :(得分:0)

使用AtomicReference变量。

using System.Collections.Generic;
using UnityEngine;


public class Player : MonoBehaviour
{
    private void Start()
    {
        FindAllChildren(transform, "Blood", out var bloodParticles);

        print(bloodParticles.Count);
    }
    
    private void FindAllChildren(Transform parent, string name, out List<Transform> list)
    {
        list = new List<Transform>();
        
        foreach (Transform child in parent)
        {
            if (child.name == name)
            {
                list.Add(child);
            }

            FindAllChildren(child, name, out list);
        }
    }
}

输出

AtomicReference<Double> temp = new AtomicReference<>();
temp.set(356.65);

Double[] values = {23.4, 45.6,9.4,1.43};

Stream.of(values).forEach(val -> {
          temp.set(temp.get() - val);
});

System.out.println(temp.get());