【问题标题】:Using groupingby with java streams将 groupingby 与 java 流一起使用
【发布时间】:2020-07-30 01:51:59
【问题描述】:

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

我正在尝试得出部分和会话的结果。 例如: 我们有一系列不同部分和课程的学生:

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

现在我必须在考虑部分和会话的情况下得出总体结果。

所以对于上述数据,我们应该看到: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 不能是一个组合。 或者有其他方法可以实现吗?

请帮忙

【问题讨论】:

  • 你也尝试过吗?您可以从groupingBy 部分开始,然后是partitioningBy 结果,然后以counting..结束。

标签: java java-8 java-stream groupingby


【解决方案1】:

您可以先使用 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())));

【讨论】:

  • 欢迎询问您是否遇到任何问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
相关资源
最近更新 更多