0

how would I do GroupingBy for the following?

I have two Map schoolsByShortName and schoolsByChair

Map schoolsByShortName = new HashMap();
Map schoolsByChair = new HashMap();

for(School school: List.getSchools()){
    if(school.getChairs()!= null){
        for(Chair chair: school.getChairs()){
            if(chair.getPrimaryChair()){
                List<School> schools = this.schoolsByChair.get(chair.getInitials());
                if(schools == null){
                    schools = new ArrayList<>();
                    this.schoolsByChair.put(chair.getInitials(), schools);
                }
                schools.add(school);
            }
        }
    }
    if(school.getShortName()!=null){
        this.schoolsByShortName.put(school.getShortName(), school);
    }
} 
dilbert2219
  • 132
  • 2
  • 10

1 Answers1

1

Something along the lines of this. Map stores as a set as I imagine each school entry should be unique. You can utilize a different Collection as needed.

        Function<School, String> getSchoolsPrimaryChairInitials = school -> school.getChairs()
                .stream()
                .filter(Chair::isPrimaryChair)
                .findFirst()
                .get()//consider possibility of not having primary chair
                .getInitials();

        Map<String, Set<School>> schoolsByChair = schools
                .stream()
                .collect(Collectors.groupingBy(getSchoolsPrimaryChairInitials, Collectors.toSet()));

        Map<String, Set<School>> schoolsByShortName = schools
                .stream()
                .collect(Collectors.groupingBy(School::getShortName, Collectors.toSet()));
Reger05
  • 233
  • 1
  • 12