Java Stream.collect using groupingBy

Viewed 74

I have a small snippet of code where I want to group the results by a combination of 2 properties of the type in the stream. After appropriate filtering, I do a map where I create an instance of a simple type that holds those 2 properties (in this case called AirportDay). Now I want to group them together and order them descending by the count. The trouble I am having is coming up with the correct arguments for the groupingBy method. Here is my code so far:

final int year = getYear();
final int limit = getLimit(10, 1, 100);

repository.getFlightStream(year)
          .filter(f -> f.notCancelled())
          .map(f -> new AirportDay(f.getOriginAirport(), f.getDate()))
          .collect(groupingBy( ????? , counting()))      // stuck here
          .entrySet()
          .stream()
          .sorted(comparingByValue(reverseOrder()))
          .limit(limit)
          .forEach(entry -> {
             AirportDay key = entry.getKey();
             printf("%-30s\t%s\t%,10d\n", 
                    key.getAirport().getName(), 
                    key.getDate(), 
                    entry.getValue()
             );
          });

My first instinct was to pass AirportDay::this but that obviously doesn't work...

I'd appreciate any assistance you can provide in coming up with a solution to the above problem.

-Tony

1 Answers

If you want to group by AirportDay, provide the function to create the key to groupingBy:

repository.getFlightStream(year)
      .filter(f -> f.notCancelled())
      .collect(groupingBy(f -> new AirportDay(f.getOriginAirport(), f.getDate()), counting()))

Note: The AirportDay class must implement sensible equals() and hashCode() methods for this to work.

Related