From 23372c2c36b73b0aa8df4d4c07e82e85efc134ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Victor=20No=C3=ABl?= Date: Sun, 27 Dec 2020 17:28:40 +0100 Subject: [PATCH] (#1475) Evaluate source once per AvgOf invocation --- src/main/java/org/cactoos/scalar/AvgOf.java | 28 ++++++--------------- 1 file changed, 8 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/cactoos/scalar/AvgOf.java b/src/main/java/org/cactoos/scalar/AvgOf.java index b3301c2130..68a9563dc7 100644 --- a/src/main/java/org/cactoos/scalar/AvgOf.java +++ b/src/main/java/org/cactoos/scalar/AvgOf.java @@ -25,9 +25,11 @@ import java.math.BigDecimal; import java.math.MathContext; +import java.util.List; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; +import org.cactoos.list.ListOf; /** * Average of numbers. @@ -50,16 +52,7 @@ *

There is no thread-safety guarantee. * * @since 0.24 - * @checkstyle ExecutableStatementCountCheck (500 lines) - * @checkstyle NPathComplexityCheck (500 lines) */ -@SuppressWarnings( - { - "PMD.CallSuperInConstructor", - "PMD.OnlyOneConstructorShouldDoInitialization", - "PMD.ConstructorOnlyInitializesOrCallOtherConstructors" - } -) public final class AvgOf extends NumberEnvelope { /** @@ -136,22 +129,17 @@ public AvgOf(final Scalar... src) { public AvgOf(final Iterable> src) { super( new Ternary<>( - new LengthOf(src), - (Double len) -> len > 0, - len -> new Folded( + new ScalarOf<>(() -> new ListOf<>(new Mapped(Scalar::value, src))), + (List list) -> !list.isEmpty(), + list -> new Folded( BigDecimal.ZERO, (sum, value) -> sum.add(value, MathContext.DECIMAL128), - new Mapped<>( - number -> BigDecimal.valueOf( - number.value().doubleValue() - ), - src - ) + new Mapped<>(s -> new BigDecimal(s.doubleValue()), list) ).value().divide( - BigDecimal.valueOf(len), + BigDecimal.valueOf(list.size()), MathContext.DECIMAL128 ).doubleValue(), - len -> 0.0 + list -> 0.0 ) ); }