Grouping objects by two fields using Java 8

  • A+
Category:Languages

I have a problem grouping two values with Java 8.

My main problem is about grouping two fields, I group correctly one field called getNameOfCountryOrRegion() but now I am interested in groupingBy another field that is called leagueDTO as well.

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

And the following class :

public class FullCalendarDTO  {     private long id;     private TeamDTO localTeam;     private TeamDTO visitorTeam;     private LocationDTO location;        private String leagueDTO;            private String timeStamp;     private String nameOfCountryOrRegion; } 

The result will be grouped by nameOfCountryOrRegion and leagueDTO.

 


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>>>.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: