Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of chaining reduce with Java 8

Tags:

java

java-8

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?

like image 799
Henkes Avatar asked Jul 05 '17 12:07

Henkes


People also ask

Can we use multiple filters in Java 8?

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.

Is method chaining possible in Java?

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.

What is function chaining in Java 8?

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.


1 Answers

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); 
like image 131
Eran Avatar answered Sep 24 '22 01:09

Eran