java-8 - 坚持使用 Java 8 流

我正在尝试学习如何在 Java 8 中使用 Streams,但不确定如何在此处着手。

我有一个类(class)列表。我需要知道一个学期的所有类(class)是否都没有学生,如果是这样,就做点什么。我想出了下面的代码,但是一旦迭代任何没有任何学生的类(class),这就会给出 Null Pointer Exception。我需要知道如何更正它:

List<Student> students = semester.getCourses().stream().flatMap(course -> course.getStudents().stream())
                .filter(Objects :: nonNull).collect(toList());
        if (CollectionUtils.isEmpty(students)){
            //cancel the semester or do something
        }

public class Semester{

 int semId;
 List<Course> courses;
}

public class Course{
 int courseId;
 List<Student> students;
}

最佳答案

在实际代码中 NullPointerException 可能来自 coursenullcourse.getStudents()
这个过滤器 filter(Objects::nonNull) 很无奈。它不会过滤 null Student,这不是您的要求。
此代码应该是您要查找的代码:

List<Student> students = 
 semester.getCourses()
         .stream()
         .filter(Objects::nonNull) // filter out null Course objects
         .map(Course::getStudents)  
         .filter(Objects::nonNull) // filter out null Student List
         .flatMap(Collection::stream)                                        
         .collect(toList());

另请注意,到处添加空检查并不好:它会降低“真实逻辑”的可读性。
您至少可以通过在声明中初始化集合字段来避免这些字段,例如:

public class Semester{
 int semId;
 List<Course> courses = new ArrayList<>();
}

public class Course{
 int courseId;
 List<Student> students = new ArrayList<>();
}

https://stackoverflow.com/questions/52763226/

相关文章:

jenkins - 本地 Jenkins 服务器没有 slave.jar 或 slave-agent

xcode - 如何禁用 Xcode 4 控制台换行?

正则表达式 - 反向引用 - 单词定界符?

https - 从 self 管理的 Let's Encrypt 到 AWS Certificate

spring - 在 Spring RestTemplate 中设置 Authorization h

amazon-web-services - AWS EKS 添加受限于命名空间的用户

fonts - Webstorm with Java 1.8,字体粗细改变

scala - scala 中的 RESTful http DELETE 方法(玩 2.0)

c# - 如何在 C# 中创建嵌套(父子)JSON 响应?

twitter-bootstrap - Bootstrap 4 导航栏,带有品牌中心和左侧、中心和右