I have list of transaction object as shown below :
List<Transaction> transactions = Arrays.asList(
new Transaction(brian, 2011, 300, "X", "M1"),
new Transaction(raoul, 2012, 1000, "T", "M1"),
new Transaction(raoul, 2011, 400, "S", "M2"),
new Transaction(mario, 2012, 710, "X", "M1"),
new Transaction(mario, 2012, 700, "X", "M2"),
new Transaction(alan, 2012, 950, "T", "M1")
);
Transaction Class :
class Transaction {
private final Trader trader;
private final int year;
private final int value;
private String type;
private String method;
}
Now I need to find the average based on type of transaction per group and finally dump the average into a Result object with some additional data about group whose avg is being computed etc.
prior to computing. following operation are performed on the list :
- grouping the transaction with year
- then grouping by method
and the final object produced should have average, year and method's value in it.
Result Class :
class Result {
private Double avg;
private int year;
private String method;
}
Code:
Map<Integer, Map<String, Result>> res = transactions.stream().collect(
groupingBy(Transaction::getYear,
groupingBy(Transaction::getMethod),
collectingAndThen( averagingDouble( t -> "X".equals(t.getType()) ? 1: 0 ),
v -> new Result(v, GROUP_METHOD? , GROUP_YEAR?))
)
);
But the GROUP_METHOD & GROUP_YEAR values are not accessible here based on which grouping is done since averagingDouble() produces a double and all other information is lost in this mapping.
is there any way we can grab these fields or to properly map the result into a object ?