java 8stream ListOdsMaterialbomItem realDiff 将字段unit相同的行上的quantity相加并且quantity是BigDecimal类型不能损失精度
可以使用Java 8的Stream API来实现这个功能。首先,我们可以使用groupingBy方法将列表中相同unit字段的行分组。然后,对于每个分组,我们可以使用reduce方法将quantity相加。最后,我们可以使用map方法将结果转换为List
以下是实现这个功能的示例代码:
List<OdsMaterialbomItem> result = realDiff
.stream()
.collect(Collectors.groupingBy(OdsMaterialbomItem::getUnit))
.entrySet()
.stream()
.map(entry -> {
BigDecimal totalQuantity = entry.getValue()
.stream()
.map(OdsMaterialbomItem::getQuantity)
.reduce(BigDecimal.ZERO, BigDecimal::add);
OdsMaterialbomItem item = entry.getValue().get(0);
return new OdsMaterialbomItem(item.getId(), item.getMaterialNo(), item.getMaterialName(),
item.getUnit(), totalQuantity);
})
.collect(Collectors.toList());
在上面的代码中,我们首先使用groupingBy方法将列表中相同unit字段的行分组。然后,对于每个分组,我们使用reduce方法将quantity相加并得到totalQuantity。接下来,我们获取每个分组中的第一个元素,然后使用它的其他字段和totalQuantity创建一个新的OdsMaterialbomItem对象。最后,我们将结果收集到一个List中并返回
原文地址: https://www.cveoy.top/t/topic/hq0j 著作权归作者所有。请勿转载和采集!