我想采取以下方法:
public BigDecimal mean(List<BigDecimal> bigDecimals, RoundingMode roundingMode) {
BigDecimal sum = BigDecimal.ZERO;
int count=0;
for(BigDecimal bigDecimal : bigDecimals) {
if(null != bigDecimal) {
sum = sum.add(bigDecimal);
count++;
}
}
return sum.divide(new BigDecimal(count), roundingMode);
}
并使用Streams api更新它。这是我到目前为止所得到的:
public BigDecimal average(List<BigDecimal> bigDecimals, RoundingMode roundingMode) {
BigDecimal sum = bigDecimals.stream()
.map(Objects::requireNonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
long count = bigDecimals.stream().filter(Objects::nonNull).count();
return sum.divide(new BigDecimal(count), roundingMode);
}
有没有办法在没有流式传输两次的情况下这样做(第二次得到计数)?
答案 0 :(得分:16)
BigDecimal[] totalWithCount
= bigDecimals.stream()
.filter(bd -> bd != null)
.map(bd -> new BigDecimal[]{bd, BigDecimal.ONE})
.reduce((a, b) -> new BigDecimal[]{a[0].add(b[0]), a[1].add(BigDecimal.ONE)})
.get();
BigDecimal mean = totalWithCount[0].divide(totalWithCount[1], roundingMode);
对于那些有帮助的代码的可选文本描述(如果您发现代码足够自我解释,请忽略。):
a
的{{1}}值包含第一个元素中的部分和和第二个元素中的部分计数。 (a,b)
元素的第一个元素包含要添加到总和中的每个BigDecimal值。 b
的第二个元素未使用。答案 1 :(得分:9)
您不需要两次流式传输。只需拨打List.size()
以获取计数:
public BigDecimal average(List<BigDecimal> bigDecimals, RoundingMode roundingMode) {
BigDecimal sum = bigDecimals.stream()
.map(Objects::requireNonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return sum.divide(new BigDecimal(bigDecimals.size()), roundingMode);
}
答案 2 :(得分:5)
或者,您可以使用此收集器实现:
class BigDecimalAverageCollector implements Collector<BigDecimal, BigDecimalAccumulator, BigDecimal> {
@Override
public Supplier<BigDecimalAccumulator> supplier() {
return BigDecimalAccumulator::new;
}
@Override
public BiConsumer<BigDecimalAccumulator, BigDecimal> accumulator() {
return BigDecimalAccumulator::add;
}
@Override
public BinaryOperator<BigDecimalAccumulator> combiner() {
return BigDecimalAccumulator::combine;
}
@Override
public Function<BigDecimalAccumulator, BigDecimal> finisher() {
return BigDecimalAccumulator::getAverage;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
@NoArgsConstructor
@AllArgsConstructor
static class BigDecimalAccumulator {
@Getter private BigDecimal sum = BigDecimal.ZERO;
@Getter private BigDecimal count = BigDecimal.ZERO;
BigDecimal getAverage() {
return BigDecimal.ZERO.compareTo(count) == 0 ?
BigDecimal.ZERO :
sum.divide(count, 2, BigDecimal.ROUND_HALF_UP);
}
BigDecimalAccumulator combine(BigDecimalAccumulator another) {
return new BigDecimalAccumulator(
sum.add(another.getSum()),
count.add(another.getCount())
);
}
void add(BigDecimal successRate) {
count = count.add(BigDecimal.ONE);
sum = sum.add(successRate);
}
}
}
并使用它:
BigDecimal mean = bigDecimals.stream().collect(new BigDecimalAverageCollector());
注意:示例使用Project Lombok注释来缩短粘合代码。
答案 3 :(得分:2)
如果您不介意第三方依赖关系,则以下Eclipse Collections Collectors2.summarizingBigDecimal()
可通过getAverage
调用MathContext
来处理RoundingMode
,其中包含{ {1}}。
MutableDoubleList doubles = DoubleLists.mutable.with(1.0, 2.0, 3.0, 4.0);
List<BigDecimal> bigDecimals = doubles.collect(BigDecimal::new);
BigDecimal average =
bigDecimals.stream()
.collect(Collectors2.summarizingBigDecimal(e -> e))
.getAverage(MathContext.DECIMAL32);
Assert.assertEquals(BigDecimal.valueOf(2.5), average);
可以添加getAverage
版本以接受RoundingMode
。
注意:我是Eclipse Collections的提交者。
答案 4 :(得分:0)
I didn't want to count the size of my stream. Then, I developed the following using accumulator and combiner.
Stream<BigDecimal> bigDecimalStream = ...
BigDecimalAverager sum = bigDecimalStream.reduce(new BigDecimalAverager(),
BigDecimalAverager::accept,
BigDecimalAverager::combine);
sum.average();
and, here is the code for the identity class;
class BigDecimalAverager {
private final BigDecimal total;
private final int count;
public BigDecimalAverager() {
this.total = BigDecimal.ZERO;
this.count = 0;
}
public BigDecimalAverager(BigDecimal total, int count) {
this.total = total;
this.count = count;
}
public BigDecimalAverager accept(BigDecimal bigDecimal) {
return new BigDecimalAverager(total.add(bigDecimal), count + 1);
}
public BigDecimalAverager combine(BigDecimalAverager other) {
return new BigDecimalAverager(total.add(other.total), count + other.count);
}
public BigDecimal average() {
return count > 0 ? total.divide(new BigDecimal(count), RoundingMode.HALF_UP) : BigDecimal.ZERO;
}
}
It is up to you how to round the divided value though (I use RoundingMode.HALF_UP for my case).
The above is similar to the way explained in https://stackoverflow.com/a/23661052/1572286
答案 5 :(得分:0)
我使用上述方法来获取BigDecimal对象列表的平均值。该列表允许使用空值。
public BigDecimal bigDecimalAverage(List<BigDecimal> bigDecimalList, RoundingMode roundingMode) {
// Filter the list removing null values
List<BigDecimal> bigDecimals = bigDecimalList.stream().filter(Objects::nonNull).collect(Collectors.toList());
// Special cases
if (bigDecimals.isEmpty())
return null;
if (bigDecimals.size() == 1)
return bigDecimals.get(0);
// Return the average of the BigDecimals in the list
return bigDecimals.stream().reduce(BigDecimal.ZERO, BigDecimal::add).divide(new BigDecimal(bigDecimals.size()), roundingMode);
}