Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aggregate multiple fields using Collectors in Java

I have a custom Object Itemized which has two fields amount and tax. I have an array of Itemized objects and I am looking to sum the two fields in the same stream. Below is how I am calculating the sum of both the fields.

double totalAmount = Arrays.stream(getCharges()).map(Itemized::getAmount).reduce(0.0, Double::sum));
double totalTax = Arrays.stream(getCharges()).map(Itemized::getTax).reduce(0.0, Double::sum));

Is there any way I don't have to parse the stream two times and can sum the two fields in one go ? I am not looking to sum totalTax and totalAmount but want their sum separately. I was looking at Collectors but was not able to find any example which would allow aggregating of multiple fields in one go.

like image 949
Nick T Avatar asked Oct 04 '19 02:10

Nick T


1 Answers

use a for loop ?

double taxSum = 0;
double amountSum = 0;
for (Itemized itemized : getCharges()) {
    taxSum += itemized.getTax();
    amountSum += itemized.getAmount();
}
like image 146
NimChimpsky Avatar answered Oct 12 '22 11:10

NimChimpsky