可以使用Java 8中的Stream API和Collectors.groupingBy()方法来实现:

List<OdsMaterialDocumentItem> items = // 获取原始数据列表

// 使用groupingBy()方法将items按照material字段分组,然后通过mapValues()方法使用reduce()方法合并每个分组中的元素
Map<String, OdsMaterialDocumentItem> mergedItems = items.stream()
        .collect(Collectors.groupingBy(OdsMaterialDocumentItem::getMaterial,
                Collectors.reducing(new OdsMaterialDocumentItem(), (item1, item2) -> {
                    BigDecimal quantity1 = new BigDecimal(item1.getQuantityInEntryUnit());
                    BigDecimal quantity2 = new BigDecimal(item2.getQuantityInEntryUnit());
                    BigDecimal mergedQuantity = quantity1.add(quantity2);
                    item1.setQuantityInEntryUnit(mergedQuantity.toPlainString());
                    return item1;
                })));

// 将合并后的元素重新转换为List对象
List<OdsMaterialDocumentItem> result = new ArrayList<>(mergedItems.values());

上述代码中,我们首先使用groupingBy()方法将items按照material字段分组,然后使用reducing()方法将每个分组中的元素合并。在合并过程中,我们将每个元素的quantityInEntryUnit字段转换为BigDecimal对象,并使用add()方法将它们相加,然后再将结果转换为String并保存到第一个元素中。最后,我们使用mapValues()方法将合并后的元素转换为List对象

java8 利用stream合并ListOdsMaterialDocumentItem items 中字段material相同的数量quantityInEntryUnit字段quantityInEntryUnit为string不能损失精度并且结果还是转为List对象

原文地址: https://www.cveoy.top/t/topic/ht34 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录