I am trying to summarize Bigdecimal field, using jOOλ library (https://github.com/jOOQ/jOOL)
This is my code, but it works only for summarizing Doubles. Here I sum field x, and grouping by fields 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());
});
Is there a way to use BigDecimal instead Double, using that library? I need to use only BigDecimal, because I want to use it to summarize financial operations.
Any help would be appreciated.
The problem isn't related to jOOλ directly, but to your usage of the JDK's standard Collector
that produces doubles as indicated by the method name:
Collectors.summarizingDouble(t -> t.x)
j ships with its own set of Collector
construction API in org.jooq.lambda.Agg
. In your case, you want to use Agg.sum(Function)
.
Obviously, change your class A
, first:
class A {
final int w;
final BigDecimal x;
final int y;
final int z;
...
}
And then:
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)));
});