java-8 – 坚持使用Java 8流
发布时间:2020-12-15 08:27:37 所属栏目:Java 来源:网络整理
导读:我正在尝试学习如何在 Java 8中使用Streams,但我不知道如何在这里进行操作. 我有一份课程清单.我需要知道一个学期的所有课程是否都没有学生,如果是这样,那就做点什么.我想出了下面的代码,但是只要任何课程被迭代而没有任何学生,这就会给出Null Pointer Excep
我正在尝试学习如何在
Java 8中使用Streams,但我不知道如何在这里进行操作.
我有一份课程清单.我需要知道一个学期的所有课程是否都没有学生,如果是这样,那就做点什么.我想出了下面的代码,但是只要任何课程被迭代而没有任何学生,这就会给出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可能来自当前为null或course.getStudents()为null.
这个过滤器过滤器(Objects :: nonNull)很无奈.它不会过滤null学生,这不是您的要求. 此代码应该是您正在寻找的: 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<>(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |