I am very new to streams in java 8 so my approach could be wrong.
I have 2 objects as follows
object1 {
BigDecimal amount;
Code1 code1;
Thanks to JB Nizet for pointing me in the right direction. I had to modify my object2
public class CodeSummary {
Double amount;
CodeKey key;
//getters and setters
}
public class CodeKey {
String code1;
String code2;
String code3;
//getters and setters
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CodeKey)) return false;
CodeKey that = (CodeKey) o;
if (!code1.equals(that.code1)) return false;
if (!code2.equals(that.code2)) return false;
if (!code3.equals(that.code3)) return false;
return true;
}
@Override
public int hashCode() {
int result = code1.hashCode();
result = 31 * result + code2.hashCode();
result = 31 * result + code3.hashCode();
return result;
}
}
iterate over object1 and populate object2. Once i had my object2 (now codeSymmary) populated. i could use the method below to do the job.
Map<CodeKey, Double> summaryMap = summaries.parallelStream().
collect(Collectors.groupingBy(CodeSummary::getKey,
Collectors.summingDouble(CodeSummary::getAmount))); // summing the amount of grouped codes.
If anyone is using this as an example. then make sure you override the equal and hashcode function in your key object. else grouping will not work.
Hope this helps someone