我有一个BigDecimals list 。

List<BigDecimal> amounts = new ArrayList<>()

如何使用Java 8流获取上述列表的摘要统计信息,而又不损失BigDecimal的多达3-4个小数位的精度?

最佳答案

我创建了this answer的通用摘要统计信息收集器的BigDecimal专用化,可以将其扩展为也支持求和,因此还可以计算平均值:

/**
 * Like {@code DoubleSummaryStatistics}, {@code IntSummaryStatistics}, and
 * {@code LongSummaryStatistics}, but for {@link BigDecimal}.
 */
public class BigDecimalSummaryStatistics implements Consumer<BigDecimal> {

    public static Collector<BigDecimal,?,BigDecimalSummaryStatistics> statistics() {
        return Collector.of(BigDecimalSummaryStatistics::new,
            BigDecimalSummaryStatistics::accept, BigDecimalSummaryStatistics::merge);
    }
    private BigDecimal sum = BigDecimal.ZERO, min, max;
    private long count;

    public void accept(BigDecimal t) {
        if(count == 0) {
            Objects.requireNonNull(t);
            count = 1;
            sum = t;
            min = t;
            max = t;
        }
        else {
            sum = sum.add(t);
            if(min.compareTo(t) > 0) min = t;
            if(max.compareTo(t) < 0) max = t;
            count++;
        }
    }
    public BigDecimalSummaryStatistics merge(BigDecimalSummaryStatistics s) {
        if(s.count > 0) {
            if(count == 0) {
                count = s.count;
                sum = s.sum;
                min = s.min;
                max = s.max;
            }
            else {
                sum = sum.add(s.sum);
                if(min.compareTo(s.min) > 0) min = s.min;
                if(max.compareTo(s.max) < 0) max = s.max;
                count += s.count;
            }
        }
        return this;
    }

    public long getCount() {
        return count;
    }

    public BigDecimal getSum()
    {
      return sum;
    }

    public BigDecimal getAverage(MathContext mc)
    {
      return count < 2? sum: sum.divide(BigDecimal.valueOf(count), mc);
    }

    public BigDecimal getMin() {
        return min;
    }

    public BigDecimal getMax() {
        return max;
    }

    @Override
    public String toString() {
        return count == 0? "empty": (count+" elements between "+min+" and "+max+", sum="+sum);
    }
}

可以与DoubleSummaryStatistics对应项类似地使用,例如
BigDecimalSummaryStatistics bds = list.stream().collect(BigDecimalSummaryStatistics.statistics());

举一个完整的例子:
List<BigDecimal> list = Arrays.asList(BigDecimal.ZERO, BigDecimal.valueOf(-2), BigDecimal.ONE);
BigDecimalSummaryStatistics bds = list.stream().collect(BigDecimalSummaryStatistics.statistics());
System.out.println(bds);
System.out.println("average: "+bds.getAverage(MathContext.DECIMAL128));

3 elements between -2 and 1, sum=-1
average: -0.3333333333333333333333333333333333

10-04 11:58