Collectors.groupingBy based on nested static class property

问题: I have a College class with nested static classes Dept College class College { private String collegeName; private Dept dept; public Dept getDept() { return dept...

问题:

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

回答1:

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())

回答2:

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.

  • 发表于 2019-01-18 10:52
  • 阅读 ( 234 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除