如何在流函数中将 String 解析为 BigDecimal,我想将属性设置为 String,然后将其解析为 BigDecimal,最后通过计算从每个对象中获取的总和来获得总和。 (目前在 BigDecimal::add 上有一条消息无法解析方法添加)谢谢。
public Optional<BigDecimal> generalTotalForSingleInvoice(PDDocument pdDocument) {
return Optional.of(new BigDecimal(findFirst(extractText(pdDocument), INVOICE_GENERAL_TOTAL)
.replaceAll("\\.", "")
.replaceAll(",", ".")).stripTrailingZeros());
}
public Optional<BigDecimal> sumOfGeneralTotal(List<PDDocument> document) {
return document.stream().map(this::generalTotalForSingleInvoice).reduce(BigDecimal.ZERO, BigDecimal::add);
}
最佳答案
您正在创建一个 Stream<Optional<BigDecimal>>
, 你不能减少 Stream
用BinaryOperator<BigDecimal>
, 所以 BigDecimal::add
不合适。
由于您的 generalTotalForSingleInvoice
永远不能返回一个空的 Optional
, 它没有理由返回 Optional
.您可以将其更改为:
public BigDecimal generalTotalForSingleInvoice(PDDocument pdDocument) {
return new BigDecimal(findFirst(extractText(pdDocument), INVOICE_GENERAL_TOTAL)
.replaceAll("\\.", "")
.replaceAll(",", ".")).stripTrailingZeros();
}
现在,您的原始 Stream
管道将工作,但请注意 reduce
您使用的变体不会返回 Optional
(因为你传递的是一个标识值),所以你应该更改方法的返回类型:
public BigDecimal sumOfGeneralTotal(List<PDDocument> document) {
return document.stream().map(this::generalTotalForSingleInvoice).reduce(BigDecimal.ZERO, BigDecimal::add);
}
关于java - 解析流函数中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59354614/