2

I am converting a List<City> into a Map<CityType, Set<City>>.

City within it has fields like CityIdentifier, State, Latitude etc.

CityIdentifier within it has a cityName & cityType.

For the above conversion, for the Collectors.groupingBy, I need a function like City::getCityType. Can I use the getter from CityIdentifier i.e. something like City::getCityIdentifier.getCityType?

Sanchay
  • 1,053
  • 1
  • 16
  • 33

1 Answers1

2

You can't use a method reference in this example.

Use a lambda expression instead:

city -> city.getCityIdentifier().getCityType()

And the full pipeline:

Map<CityType, Set<City>> map =
    list.stream()
        .collect(Collectors.groupingBy(city -> city.getCityIdentifier().getCityType(),
                                       Collectors.toSet()));
Eran
  • 387,369
  • 54
  • 702
  • 768