[英]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.