使用Java 8按两个字段对对象进行分组

kik*_*kes 8 java collections grouping java-8 java-stream

我有一个问题,用Java 8分组两个值.

我的主要问题是关于分组两个字段,我正确地组合了一个字段,getNameOfCountryOrRegion()但现在我对groupingBy另一个被调用的字段感兴趣leagueDTO.

Map<String, List<FullCalendarDTO>> result = countryDTOList.stream()
               .collect(Collectors.groupingBy(
                             FullCalendarDTO::getNameOfCountryOrRegion));
Run Code Online (Sandbox Code Playgroud)

以下课程:

public class FullCalendarDTO  {
    private long id;
    private TeamDTO localTeam;
    private TeamDTO visitorTeam;
    private LocationDTO location;   
    private String leagueDTO;       
    private String timeStamp;
    private String nameOfCountryOrRegion;
}
Run Code Online (Sandbox Code Playgroud)

结果将通过分组nameOfCountryOrRegionleagueDTO.

Nam*_*man 3

如果要使用两个属性进行分组,则输出将是 a,其中Map键作为用于分组的第一个属性( getNameOfCountryOrRegion),值作为 a ,Map再次以键作为第二个属性用于分组( getLeagueDTO) ,其值作为List<FullCalendarDTO>分组的a基于指定的键。

这看起来像:

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