Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuck with Java 8 stream usage

I am trying to learn how to use Streams in Java 8 but am not sure how to go about it here.

I have a list of courses. I need to know if all the courses for a semester have no students, and if that is the case, do something. I came up with the below code but this is giving Null Pointer Exception as soon as any course gets iterated which doesn't have any students.I need to know how can i 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;
}
like image 747
T Anna Avatar asked Sep 06 '25 09:09

T Anna


2 Answers

In the actual code the NullPointerException may come from course is null or course.getStudents() is null.
This filter filter(Objects :: nonNull) is helpless. It doesn't filter the null Students and that is not your requirement.
This code should be what you are looking for :

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());

Note also that adding null checks everywhere is not good : it makes "real logic" less readable.
You can at least avoid these for collection fields by initializing them in their declarations such as :

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

public class Course{
 int courseId;
 List<Student> students = new ArrayList<>();
}
like image 101
davidxxx Avatar answered Sep 11 '25 04:09

davidxxx


boolean allCourseHaveEmptyStudens=semester.getCourses().stream()
.allMatch(c-> c.getStudents()==null || c.getStudents().size==0)
;

I think it's enough to fulfill your requirement.

Note: It might get a compilation error because I don't use editor tool.

like image 25
Huy Nguyen Avatar answered Sep 11 '25 05:09

Huy Nguyen