猿问

lambda 表达式中的错误返回类型:BigDecimal 无法转换为 long

我试图通过加速在 java 流中编写查询。当我尝试sum (l_extendedprice * (1 - l_discount))选择时,出现此错误:


lambda 表达式中的错误返回类型:BigDecimal 无法转换为 long。运算符“-”不能应用于“int”、“java.math.BigDecimal”。


我的代码是这样的:


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()))

        ));

我该如何解决这个问题?


慕标5832272
浏览 220回答 1
1回答

繁星点点滴滴

所以问题是 , +, -, *, /... 不与BigDecimals 一起工作。您必须使用.add(), .subtract(), .multiply(), .divide(), ... 方法进行计算。如果可能,您可以使用BigDecimal.longValue()orBigDecimal.longValueExact()将BigDecimals 转换为 long 值以在计算中使用它们:Map<Tuple1<String>, LongSummaryStatistics> grouped = join.stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(Tuples::of,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; () -> new TreeMap<>(comparator),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.summarizingLong(t -> t.get2().getLDiscount().longValue() *&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (1 - t.get2().getLDiscount().longValue()))&nbsp; &nbsp; &nbsp; &nbsp; ));或者,您可以使用 du 整个计算BigDecimal并在最后将值转换为 long:Map<Tuple1<String>, LongSummaryStatistics> grouped = join.stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(Tuples::of,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; () -> new TreeMap<>(comparator),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.summarizingLong(t -> t.get2().getLDiscount()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .multiply(BigDecimal.ONE&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .subtract(t.get2().getLDiscount())).longValue())&nbsp; &nbsp; &nbsp; &nbsp; ));如果这两种解决方案都不适合您,您必须编写自己的集合BigDecimalSummaryStatistics或直接计算您需要的值。您可以阅读此问题以使用 Java Stream 汇总BigDecimal值。
随时随地看视频慕课网APP

相关分类

Java
我要回答