开发者社区> 问答> 正文

Java8:在forEach之外更改变量的引用

我尝试在onc做两件事: 1.列表中对象特定字段的总和

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.从列表中过滤对象

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

有更好的解决方案吗?

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 19:48:01 3471 0
1 条回答
写回答
取消 提交回答
  • 您还必须使用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);
         }
    });
    

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

    回答来源:Stack Overflow

    2020-03-22 19:48:38
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载