【发布时间】:2020-01-08 05:49:05
【问题描述】:
我有一个列表 List<CT> 需要使用流一次更新相同的 List<CT>。
我们有两个数量字段,如果firstQty 小于secondQty,则在下一条记录中剩余的应该设置为secondQty。仅当currentMonth 指标为真时,我们才进行此计算;
输入:
none
[CT(currentMonth=tue, firstQty=600, secondQty=620,..),
CT(currentMonth=false, firstQty=0, secondQty=0,..),
CT(currentMonth=false, firstQty=0, secondQty=0,..)]
输出:
none
[CT(currentMonth=tue, firstQty=600, secondQty=620,..),
CT(currentMonth=false, firstQty=0, secondQty=20,..),
CT(currentMonth=false, firstQty=0, secondQty=0,..)]
class CT {
Boolean currentMonth;
BigDecimal firstQty;
BigDecimal secondQty;
}
List<CT> lotsDetailsTpm = deals.stream()
.map(dcl ->{
BigDecimal diffrence = BigDecimal.ZERO;
if(dcl.getCurrentMonth()) {
BigDecimal qtyFirst = deals.getFirstQty();
BigDecimal qtySecond = deals.getSecondQty();
BigDecimal diff = qtySecond.subtract(qtyFirst);
dcl.qtySecond(qtySecond.sbtract(diff));
if(diff.compareTo(BigDecimal.ZERO) > 1) {
//need to update the diff to the next element
}
}
return dcl;
}).collect(Collectors.toList());
这里的难点是如何保持数量的差异,并使用该值来更新下一个元素。
【问题讨论】:
-
不要为此使用流。它们不适合涉及元素之间此类操作的任务。
-
请添加您当前的解决方案尝试。
-
一种解决方案是使用
IntStream并循环您的集合,就像您在更经典的“for 循环”(类似于IntStream.range(0, collection.size()).forEach(i -> \*do your operations here*\);)中所做的那样。但是,我看不出这样做有什么意义:只需做一个“for循环”,它会更容易阅读。 -
@Abrikot:这只是滥用java-stream。那么我会坚持使用 for 循环。
标签: java java-8 java-stream