The words "better" or "best" should refer to some metric. Performance? Readability? Elegance?
The answer by Eran shows one approach, namely creating small streams containing the property values A, B, C and D for each associate, and flat-mapping these values into a larger stream. The order of summation in this approach is
A0 + B0 + C0 + D0 + A1 + B1 + C1 + D1 + ... + An + Bn + Cn + Dn
Another option would be to create individual streams of the properties A, B, C and D, and concatenating these streams before applying the reduction. This could be done with nested Stream#concat
calls, but more elegantly and flexibly using flatMap
with an identity function:
Stream<BigDecimal> stream = Stream.of(
entity.getAssociate().stream().map(Associates::getPropertyA),
entity.getAssociate().stream().map(Associates::getPropertyB),
entity.getAssociate().stream().map(Associates::getPropertyA),
entity.getAssociate().stream().map(Associates::getPropertyC))
.flatMap(Function.identity());
BigDecimal total = stream.reduce(BigDecimal.ZERO, BigDecimal::add);
The key point is that in this case, the summation order is
A0 + A1 + ... + An + B0 + B1 + ... + Bn + C0 + C1 + ... + Cn
(It may not technically make a large difference. But it is an approach that is conceptually different to the ones that have been proposed so far (in terms of the summation order), and thus, may be worth mentioning as one option - additionally, it is more similar to the approach that you currently use, but without the broken identity value for the reduction)