Jiumu:
私はONCで二つのことをやろう。
私はONCで二つのことをやろう。
リスト内のオブジェクトの特定のフィールドから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();
私はこのコードをしたいと思いますが、それは仕事をdoesen't:
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
。ここに関連する質問です。