Bad return type in lambda expression: BigDecimal cannot be converted to long
我试图通过速度在Java流中编写查询。 当我在选择中尝试sum (l_extendedprice * (1 - l_discount))时,出现此错误:
Bad return type in lambda expression: BigDecimal cannot be converted to long. Operator '-' cannot be applied to 'int', 'java.math.BigDecimal'.
我的代码是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
JoinComponent joinComponent = app.getOrThrow(JoinComponent.class); Join<Tuple6<Customer, Orders, Lineitem, Supplier, Nation, Region>> join = joinComponent .from(CustomerManager.IDENTIFIER) .innerJoinOn(Orders.O_CUSTKEY).equal(Customer.C_CUSTKEY) .where(Orders.O_ORDERDATE.greaterOrEqual(sqlDate)) .where(Orders.O_ORDERDATE.lessThan(sqlDate2)) .innerJoinOn(Lineitem.L_ORDERKEY).equal(Orders.O_ORDERDATE) .innerJoinOn(Supplier.S_SUPPKEY ).equal(Customer.C_NATIONKEY) .innerJoinOn(Nation.N_NATIONKEY).equal(Supplier.S_NATIONKEY) .innerJoinOn(Region.R_REGIONKEY).equal(Nation.N_REGIONKEY) .where(Region.R_NAME.equal("ASIA")) .build(Tuples::of); Comparator<Tuple1<String>> comparator = Comparator .comparing((Function<Tuple1<String>, String>) Tuple1::get0) .thenComparing(Tuple1::get0); Map<Tuple1<String>, LongSummaryStatistics> grouped = join.stream() .collect(groupingBy(t -> Tuples.of(t.get4().getNName()), () -> new TreeMap<>(comparator), summarizingLong(t->t.get2().getLDiscount()*(1-t.get2().getLDiscount())) ));
我该如何解决?
相关讨论
我猜t.get2().getLDiscount()*(1-t.get2().getLDiscount())是问题,并且getLDiscount()返回BigDecimal。 您不能说1 - BigDecimal,也不能说BigDecimal * BigDecimal。 但这只是一个假设,因为您还没有发布getLDiscount() @ElliottFrisch,公共BigDecimal getLDiscount(){return lDiscount; }
因此问题是+,-,*,/,...不适用于BigDecimal s。 您必须使用.add(),.subtract(),.multiply(),.divide(),...方法进行计算。
如果可能,可以使用BigDecimal.longValue()或BigDecimal.longValueExact()将BigDecimal转换为长值,以在计算中使用它们:
1 2 3 4 5 6
Map<Tuple1<String>, LongSummaryStatistics> grouped = join.stream() .collect(Collectors.groupingBy(Tuples::of, () -> new TreeMap<>(comparator), Collectors.summarizingLong(t -> t.get2().getLDiscount().longValue() * (1 - t.get2().getLDiscount().longValue())) ));
或者,您可以使用BigDecimal进行整个计算,并在最后将值转换为long:
1 2 3 4 5 6 7
Map<Tuple1<String>, LongSummaryStatistics> grouped = join.stream() .collect(Collectors.groupingBy(Tuples::of, () -> new TreeMap<>(comparator), Collectors.summarizingLong(t -> t.get2().getLDiscount() .multiply(BigDecimal .ONE .subtract(t.get2().getLDiscount())).longValue()) ));
如果两种解决方案都不适合您,则必须为BigDecimalSummaryStatistics编写自己的集合,或者直接计算所需的值。 您可以阅读有关使用Java Stream汇总BigDecimal值的问题。
参考:关于java:lambda表达式中的错误返回类型:BigDecimal无法转换为long | 码农家园