繁体   English   中英

对 java 流使用 groupingby

[英]Using groupingby with java streams

我有一份学生名单,请参阅 DTO。

我正在尝试得出该部分的结果和 session。 例如:我们有一组具有不同部分和课程的学生:

Students:
[Student [id=1, section=section-a, result=pass, session=2020],
Student [id=2, section=section-a, result=failed, session=2020], 
Student [id=1, section=section-b, result=passed, session=2020]]

现在我必须在考虑& session 部分的情况下得出整体结果。

所以对于上面的数据,我们应该看到: section-a, session:2020 has failed因为我们有一个不及格的学生 同样,对于第二组,即section-b, session:2020 ,结果应该通过,因为我们只有 1 个学生,这也是通过的结果


class Student {
private String id;
private String section;
private String result;
private String session;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getSection() {
    return section;
}

public void setSection(String section) {
    this.section = section;
}

public String getResult() {
    return result;
}

public void setResult(String result) {
    this.result = result;
}

public String getSession() {
    return session;
}

public void setSession(String session) {
    this.session = session;
}

@Override
public String toString() {
    return "Student [id=" + id + ", section=" + section + ", result=" + result + ", session=" + session + "]";
}

}

主要课程

public class GroupingBy {

public static void main(String[] args) {
    System.out.println("Hello world!");

    List<Student> students = new ArrayList<>();
    Student student = new Student();
    student.setId("1");
    student.setResult("pass");
    student.setSection("section-a");
    student.setSession("2020");

    Student student1 = new Student();
    student1.setId("2");
    student1.setResult("failed");
    student1.setSection("section-a");
    student.setSession("2020");

    Student student2 = new Student();
    student2.setId("1");
    student2.setResult("failed");
    student2.setSection("section-b");
    student.setSession("2020");

    students.add(student);
    students.add(student1);
    students.add(student2);

    System.out.println("Students:" + students);
}

}

我想过使用 java 流并执行 groupby 操作,这样我就可以得到这样的东西:

{section-a,2020 = passed:1, failed:1},{section-b,2020 = passed:1}

然后我可以使用上面的数据推导出最终的结果。 我试过了,但似乎 key 不能是一个组合。 还是有另一种方法可以实现这一目标?

请帮忙

您可以先使用Collectors.groupingBy按 Section 和 Session 分组,然后再按 Result 分组并使用Collectors.counting()来计算组的大小。

Map<SimpleEntry<String, String>, Map<String, Long>> map = 
        students.stream()
                    .collect(Collectors.groupingBy(
                                    e -> new AbstractMap.SimpleEntry<>(e.getSection(), e.getSession()),
                                Collectors.groupingBy(e -> e.getResult(), Collectors.counting())));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM