-1

How would I apply grouping by collectors to fill up hashmaps for the following nested loops?

GroupingBy

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);
    }
} 
John Kugelman
  • 330,190
  • 66
  • 504
  • 555

1 Answers1

0

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
  • 223
  • 1
  • 12