Java – adds multiple bigdecimals to a map
•
Java
I tried to aggregate multiple bigdecimals from the list At present, I am using two streams, but if possible, I want only one stream I'm not sure how to rewrite the following in an efficient way
BigDecimal totalCharges = tableRowDataList.stream() .map(el -> el.getSums().getCharges()) .reduce(BigDecimal.ZERO,BigDecimal::add); BigDecimal totalFees = tableRowDataList.stream() .map(el -> el.getSums().getFees()) .reduce(BigDecimal.ZERO,BigDecimal::add);
As you can see, the flows are basically the same, except for the calls to getcharges / getfees
What is the best way to get the result map < string, BigDecimal >? From above? (the key is fees / charges)
Solution
First, you create a class to collect results
Then you do it like BigDecimal, that is, the zero constant and the add () method
public class ChargesAndFees { private static final ZERO = new ChargesAndFees(BigDecimal.ZERO,BigDecimal.ZERO); private final BigDecimal charges; private final BigDecimal fees; // constructor and getters public ChargesAndFees add(ChargesAndFees that) { return new ChargesAndFees(this.charges.add(that.charges),this.fees.add(that.fees)); } }
Now you can do flow logic
ChargesAndFees totals = tableRowDataList.stream() .map(el -> new ChargesAndFees(el.getSums().getCharges(),el.getSums().getFees())) .reduce(ChargesAndFees.ZERO,ChargesAndFees::add);
If you insist, you can convert the value in the total to map
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码