Collectors.groupingBy based on nested static class property

Viewed 281

I have a College class with nested static classes Dept

College

class College {
private String collegeName;

private Dept dept;

public Dept getDept() {
    return dept;
}

public void setDept(Dept dept) {
    this.dept = dept;
}

public String getCollegeName() {
    return CollegeName;
}

public void setCollegeName(String collegeName) {
    CollegeName = collegeName;
}

public static class Dept {

    private String deptName;

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
        }

    }

 }

I have list of College objects and trying to groupingBy based on deptName i,e (Map<String>, List<College>), But no luck so far and it gives a compilation error message

List<College> list = new ArrayList<College>();
list.stream().collect(Collectors.groupingBy(College.Dept::getDeptName));

Compile Error

The method collect(Collector<? super College,A,R>) in the type Stream<College> is not applicable for the arguments (Collector<College.Dept,capture#1-of ?,Map<String,List<College.Dept>>>)
2 Answers
College.Dept::getName

is a Function<College.Dept, String>. It doesn't accept a College as an input.

Use a lambda to construct a Function<College, String>:

groupingBy(c -> c.getDept().getName())

You can try this:

Map<String, List<College>> map = 
         list.stream()
             .collect(groupingBy(college -> college.getDept().getDeptName()));

Update:

These two observations may be off topic, though I believe they're worth mentioning:

  1. Is the identifier of class property CollegeName capitalized intentionally? I would highly recommend using the same coding style all over your code.

  2. Looks like you need to rethink your data hierarchy (even if it's just a tutorial task). The relation between College and Dept shouldn't be one-to-one, but one-to-many instead.

Related