I have the following code that I'm trying to improve:
BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA) .reduce(BigDecimal.ZERO, BigDecimal::add); total = entity.getAssociate().stream().map(Associates::getPropertyB) .reduce(total, BigDecimal::add); total = entity.getAssociate().stream().map(Associates::getPropertyC) .reduce(total, BigDecimal::add); total = entity.getAssociate().stream().map(Associates::getPropertyD) .reduce(total, BigDecimal::add);
It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?
Overview However, we'll learn how to use the filter() method with as many condition filters as we require. More filters can be applied in a variety of methods, such using the filter() method twice or supplying another predicate to the Predicate. and() method.
Method chaining in Java is a common syntax to invoke multiple methods calls in OOPs. Each method in chaining returns an object. It violates the need for intermediate variables.
Function in Java 8A Function is a functional interface (has a single abstract method called accept) that accepts one argument and produces a result. Example: We can create a stream of integers, map each integer element to double (2x) of its value, and collect the result as a list.
If all these properties are of the same type (it seems they are all BigDecimal
), you can use flatMap
to create a single Stream
of them all and then reduce
it to the total sum:
BigDecimal total = entity.getAssociate() .stream() .flatMap (a -> Stream.of(a.getPropertyA(),a.getPropertyB(),a.getPropertyC(),a.getPropertyD())) .reduce(BigDecimal.ZERO, BigDecimal::add);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With