Java-8 – stick with Java 8 streams

I'm trying to learn how to use streams in Java 8, but I don't know how to operate here

I have a list of courses I need to know if there are no students in all courses in a semester. If so, do something I came up with the following code, but as long as any course is iterated without any students, this will give a null pointer exception I need to know how to correct it:

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;
}

Solution

In actual code, the NullPointerException may come from a currently null or course Getstudents() is 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());

Also note that adding null checking anywhere is bad: it makes "real logic" less readable You can avoid at least these for collection fields by initializing them in the declaration, for example:

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

public class Course{
 int courseId;
 List<Student> students = new ArrayList<>();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>