I have the following nested groupingBy block:
Map<String,Map<String,Long>> namesCountersMap =
events.stream().collect(
Collectors.groupingBy(
namesDAO::getName,
Collectors.groupingBy(
genericDAO::SOME_DYNAMIC_FIELD,
Collectors.counting())
)
);
There is a situation where I need to call this block 3 times, and the only thing I change is the inner groupingBy field ("SOME_DYNAMIC_FIELD").
Basically what i'm trying to do, is to use group-by and counting for a different field (at the second level) every time, and then merge the results.
Example:
{
"NamesRecords": {
"Sam": {
"Cars": 4
"Bags": 6
"Houses": 2
},
"Bob": {
"Cars": 2
"Bags": 1
"Houses": 3
},
}
}
As you can see, group-by at the 2nd level is done by 3 different fields, that's is why I need to duplicate this block of code three times.
If I pass a parameter of fieldToGroupBy to the function, is there a way I can use it dynamically? Or if you have any other ideas of how to avoid code duplication, I would love to hear.