简体   繁体   中英

java stream null check

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM