我想在Collection with Streams中计算集合中的集合数

Tre*_*vor 2 java java-8 java-stream

假设我有一个SchoolDistrict,有许多Schools,有许多Students有很多Classes.

我想计算给予SchoolDistrict的课程数量.

Java 7的方式是这样的:

Integer classCount = 0;
for (School school : schoolDistrict)
{
    for (Student student : school.getStudents())
    {
        classCount += student.getClasses().size();
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道Java 8带来的流应该会使这种事情在眼睛上变得容易一些.

但我无法弄清楚如何去做.

任何接受者?

编辑:有人将此标记为此帖的副本,我不相信这是因为该示例仅深入2级(国家/地区).我的问题涉及一个深入四个层次的问题(SchoolDistricts to Schools to Students to Classes)

Boh*_*ian 6

这使用方法引用来完成没有lambda的工作:

int classCount = schoolDistrict.stream()
  .map(School::getStudents)
  .flatMap(Collection::stream)
  .map(Student::getClasses)
  .mapToInt(Collection::size)
  .sum();
Run Code Online (Sandbox Code Playgroud)

另请注意,切换到每个学生班级IntStream大小然后应用sum(),这当然比为每个学生流式传输每个班级并迭代计算班级更有效.