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.
Probably, I have two object Student, Employe & finding only those object which have same name and id, rather employe and student coming from database, that may be chance to wether any field cab be null.
I would suggest changing your database schema to prohibit null values, especially on your primary keys - id. Implementing this at the database layer will definitely help you in the long run so you don't have to manually examine your results in Java. Good luck! :-)