我尝试在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
您还必须使用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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。