我们如何在java8中的DoubleSummaryStatistics对象中自定义count,avg,sum,min和max的顺序

sur*_*day 5 java java-8

我按以下格式获得低于输出,这是我认为的默认值.

{"count":100,"sum":25640.13,"min":2.65,"max":483.91,"average":256.4013}
Run Code Online (Sandbox Code Playgroud)

但我想改变这种格式如下.

{"sum":"25640.13","avg":"256.40","max":"483.91","min":"2.65","count":100}
Run Code Online (Sandbox Code Playgroud)

下面我在java类中使用的代码.

 @Override
public DoubleSummaryStatistics getStatistic() {
    logger.info("Getting statistic");
    Set<Entry<Long, Transaction>> endtrySet = statisticHistory.entrySet();
    List<Double> amountList = new ArrayList<>();

    for (Entry<Long, Transaction> entry : endtrySet) {
        if (((entry.getValue().getDate())).isAfter(Instant.now().minusSeconds(windowInMs)))
            amountList.add((entry.getValue().getAmount()).doubleValue());
    }
    return amountList.stream().mapToDouble((x) -> x).summaryStatistics();

}
Run Code Online (Sandbox Code Playgroud)

如何重新排列json格式?

为了更好的理解,用简单的语法粘贴上面的方法.示例代码方法..

    public DoubleSummaryStatistics getStatisdtic() {
    logger.info("Getting statistic");
    Set<BigDecimal> endtrySet = null ; //= getting this from a other resource
    List<Double> amountList = new ArrayList<>();

    for (BigDecimal entry : endtrySet) {
            amountList.add((entry).doubleValue());
    }
    return amountList.stream().mapToDouble((x) -> x).summaryStatistics();

}
Run Code Online (Sandbox Code Playgroud)

Eug*_*ene 2

由于您无法编辑DoubleSummaryStatistics(您无法在其中添加自己的 json 特定注释),因此您可以做的就是创建自己的类,MyDoubleSummaryStatistics该类将根据您想要的任何结果创建。

但是,如果您正在调用toStringDoubleSummaryStatistics,为什么不单独调用每个字段,例如DoubleSummaryStatistics ::getAverage等等,并构建您需要/想要的任何字符串。