Warm tip: This article is reproduced from stackoverflow.com, please click
java stream

java stream null check

发布于 2020-04-11 22:23:09

How to better way to check null values inside stream

List<Employee> employees1= employees.stream().filter(
                    employee -> students.stream()
                        .anyMatch(student ->
                               // checking null
                                employee!=null && student!=null &&
                                employee.getId()!=null && student.getName()!=null &&
                                employee.getId()==student.getId() &&
                                employee.getName().equals(student.getName()))
                )
                .collect(Collectors.toList());
Questioner
Sagir
Viewed
44
NimbleNavigator 2020-03-19 17:46

I'm curious to see if your code throws a NullPointerException during execution. You are streaming your employees collection and then a students collection within the Employee object.

If your parent object, Employee, is a null value then you cannot possibly have a student collection on that object, as indicated in your inner-stream.

Consider introducing:

.map(employee -> Optional.ofNullable(employee) 
.filter(Optional::isPresent)
.map(Optional::get) 

before your filter. This will eliminate any null parent objects.

For your inner-stream, you still seem concerned that your student element is going to be null, so repeat these lines before your .anyMatch call.

For readability, I would consider extracting your null checks into smaller methods that describe what checks are being performed. For example you have the line:

employee.getName().equals(student.getName()

which suggests that you're looking for student elements where the employee and student names match. employeeAndStudentNamesMatch(employee, student) would suffice here.

For checking null values, you should really use the Optional API. This gives you options to wrap something that is potentially null in a safe wrapper to check if there is a value there or not. Extracting an example from your inner stream where you're checking for the presence of a student's name you can replace this with:

Optional.ofNullable(student.getName()).isPresent();

This is all the advice that I can really offer. Hope it helps you progress.