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;
}
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
Student
s 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<>();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With