I am using stream group by like this in Java 8:
reportProfitResult = reportProfits.stream()
.collect(Collectors.groupingBy(ReportProfitAnalysis::getStatisticTime));
Now I want to pass the group by field as a parameter in outer founction like this:
private void MapResult(E groupByField) {
reportProfitResult = reportProfits.stream()
.collect(Collectors.groupingBy(groupByField));
}
what should I do to make it work as expect ? I have followed tips but still encount this problem:

Take a look at the documentation for groupingBy.
You need a Function<? super T,? extends K> classifier as the type, or something more specific depending on how your ReportProfitAnalysis and reportProfitResult look.
For example:
private void MapResult(Function<? super ReportProfitAnalysis, ?> func) {
reportProfitResult = reportProfits.stream()
.collect(Collectors.groupingBy(func));
}
You can pass the grouping function
Function<? super ReportProfitAnalysis, ?> func = ReportProfitAnalysis::getStatisticTime;
Note that the reportProfitResult here would be defined as Map<?, List<ReportProfitAnalysis>> reportProfitResult
In that case, the type of groupByField should be Function<ReportProfitAnalysis, ? extends K>, where K is a generic type parameter (assuming your Stream is a Stream<ReportProfitAnalysis>).
private <K> void MapResult(Function<ReportProfitAnalysis, ? extends K> groupByField)
{
reportProfitResult = reportProfits.stream()
.collect(Collectors.groupingBy(groupByField));
}
And you can call it, for example, with:
MapResult(ReportProfitAnalysis::getStatisticTime);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With