Java8:改变forEach外变量的引用

Java8: change the reference of the variable outside of forEach

我试着同时做两件事:

1.Sum 列表中对象特定字段的值

AtomicReference<BigDecimal> doReqQtySum = new AtomicReference<>(BigDecimal.ZERO);
AtomicReference<BigDecimal> boQtySum = new AtomicReference<>(BigDecimal.ZERO);
models.forEach(detail -> {
    doReqQtySum.accumulateAndGet(detail.getDoReqQty(), (bg1, bg2) -> bg1.add(bg2));
    boQtySum.accumulateAndGet(detail.getBoQty(),  (bg1, bg2) -> bg1.add(bg2));
});

2.Filter 列表中的对象

DoRequestDetailModel originProductRequestDetail = models.stream()
    .filter(m -> m.getIsOriginProduct())
    .reduce((a, b) -> {
         throw new IllegalStateException();
    })
    .get();

我想要这段代码,但它不起作用:

AtomicReference<BigDecimal> doReqQtySum = new AtomicReference<>(BigDecimal.ZERO);
AtomicReference<BigDecimal> boQtySum = new AtomicReference<>(BigDecimal.ZERO);
DoRequestDetailModel originProductRequestDetail = new DoRequestDetailModel();
models.forEach(detail -> {
     doReqQtySum.accumulateAndGet(detail.getDoReqQty(), (bg1, bg2) -> bg1.add(bg2));
     boQtySum.accumulateAndGet(detail.getBoQty(),  (bg1, bg2) -> bg1.add(bg2));
     if(detail.getIsOriginProduct()) {
          originProductRequestDetail = detail;
     }
});

下一个代码可以完成

AtomicReference<BigDecimal> doReqQtySum = new AtomicReference<>(BigDecimal.ZERO);
AtomicReference<BigDecimal> boQtySum = new AtomicReference<>(BigDecimal.ZERO);
List<DoRequestDetailModel> tempList = new ArrayList<>();
models.forEach(detail -> {
    doReqQtySum.accumulateAndGet(detail.getDoReqQty(), (bg1, bg2) -> bg1.add(bg2));
    boQtySum.accumulateAndGet(detail.getBoQty(),  (bg1, bg2) -> bg1.add(bg2));
    if(detail.getIsOriginProduct()) {
         tempList.add(detail);
    }
});

有更好的解决方案吗?

您还必须使用 AtomicReference

AtomicReference<BigDecimal> doReqQtySum = new AtomicReference<>(BigDecimal.ZERO);
AtomicReference<BigDecimal> boQtySum = new AtomicReference<>(BigDecimal.ZERO);
AtomicReference<DoRequestDetailModel> originProductRequestDetail = new AtomicReference<>(new DoRequestDetailModel());
models.forEach(detail -> {
     doReqQtySum.accumulateAndGet(detail.getDoReqQty(), (bg1, bg2) -> bg1.add(bg2));
     boQtySum.accumulateAndGet(detail.getBoQty(),  (bg1, bg2) -> bg1.add(bg2));
     if(detail.getIsOriginProduct()) {
          if(originProductRequestDetail.get()) throw new IllegalStateException();
          originProductRequestDetail.set(detail);
     }
});

这是因为您正在 forEach 内部调用的函数范围内更改外部变量的引用。 Here 是一个相关问题。