Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a function parameter in Java 8 in stream groupby

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:

enter image description here

like image 832
Dolphin Avatar asked Oct 25 '25 06:10

Dolphin


2 Answers

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

like image 94
geco17 Avatar answered Oct 27 '25 19:10

geco17


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);
like image 36
Eran Avatar answered Oct 27 '25 20:10

Eran