代码之家  ›  专栏  ›  技术社区  ›  Lev

使用jOO按属性总结BigDecimal分组

  •  1
  • Lev  · 技术社区  · 7 年前

    我试图用jOO库总结Bigdecimal字段( https://github.com/jOOQ/jOOL )

    这是我的代码,但它只适用于汇总双精度。 这里我对字段x求和,并按字段w、z分组:

    class A {
        final int w;
        final Double x;
        final int y;
        final int z;
    
        A(int w, Double x, int y, int z) {
            this.w = w;
            this.x = x;
            this.y = y;
            this.z = z;
        }
    }
    
    Map<
        Tuple2<Integer, Integer>,
        DoubleSummaryStatistics
    > map =
    Seq.of(
        new A(1, 1.01D, 1, 1),
        new A(1, 2.09D, 3, 1),
        new A(1, 8D, 6, 1),
        new A(2, 119D, 7, 2),
        new A(1, 3.01D, 4, 1),
        new A(1, 4D, 4, 1),
        new A(1, 5D, 5, 1))
    .groupBy(
        t -> tuple(t.z, t.w),
        Tuple.collectors(
            Collectors.summarizingDouble(t -> t.x)
        )
    );
    
    map.entrySet().forEach(t-> {
        log.info("w={}, z={}, sumX={}", t.getKey().v1, t.getKey().v2,
                t.getValue().getSum());
    });
    

    有没有办法用BigDecimal代替Double,使用这个库? 我只需要使用BigDecimal,因为我想用它来总结财务操作。

    任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Lukas Eder    7 年前

    这个问题与jOO没有直接关系,而是与您对JDK标准的使用有关 Collector 产生方法名称指示的双精度:

    Collectors.summarizingDouble(t -> t.x)
    

    j自带一套 收藏家 建筑空气污染指数 org.jooq.lambda.Agg .在你的情况下,你想使用 Agg.sum(Function) .

    显然,换个班 A 首先:

    class A {
        final int w;
        final BigDecimal x;
        final int y;
        final int z;
        ...
    }
    

    然后:

    Map<
        Tuple2<Integer, Integer>,
        Optional<BigDecimal>
    > map =
    Seq.of(
        new A(1, new BigDecimal("1.01"), 1, 1),
        new A(1, new BigDecimal("2.09"), 3, 1),
        new A(1, new BigDecimal("8"), 6, 1),
        new A(2, new BigDecimal("119"), 7, 2),
        new A(1, new BigDecimal("3.01"), 4, 1),
        new A(1, new BigDecimal("4"), 4, 1),
        new A(1, new BigDecimal("5"), 5, 1))
    .groupBy(
        t -> tuple(t.z, t.w),
        Agg.sum(t -> t.x)
    );
    
    map.entrySet().forEach(t-> {
        System.out.println(String.format("w=%s, z=%s, sumX=%s", t.getKey().v1, t.getKey().v2,
                t.getValue().orElse(BigDecimal.ZERO)));
    });