Henkes :
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?
Eran :
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);
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=423955&siteId=1