Grouping objects by two fields using Java 8

Passing a downstream collector to groupingBy will do the trick:

countryDTOList.stream()
              .collect(groupingBy(FullCalendarDTO::getNameOfCountryOrRegion,
                       groupingBy(FullCalendarDTO::getLeagueDTO)));

The code snippet above will group your FullCalendarDTO objects by nameOfCountryOrRegion then each group will be grouped by leagueDTO.

So the returned collection will look like Map<String, Map<String, List<FullCalendarDTO>>>.


If you were to group by using two attributes, your output would be a Map with keys as the first attribute used to group(getNameOfCountryOrRegion) and values as a Map again with keys as the second attribute used to group(getLeagueDTO) and its values as a List<FullCalendarDTO> which are grouped based on the keys specified.

This shall look like :

Map<String, Map<String, List<FullCalendarDTO>>> result = countryDTOList.stream()
        .collect(Collectors.groupingBy(FullCalendarDTO::getNameOfCountryOrRegion,
                Collectors.groupingBy(FullCalendarDTO::getLeagueDTO)));