Issue
How to check variables of Objects
are empty or NULL
in JAVA?
Employee employee = repository.getEmployee(id).orElseGet(null);
if (employee == null) {
employee = new Employee();
employee.id(1);
employee.name("Thirumal");
employee.mobile("+91-8973-697-871");
repository.save(employee);
}
Instead of NULL
, I am trying to create an object new Employee()
Employee employee = repository.getEmployee(id).orElseGet(new Employee());
if (employee.isEmpty()) { //--------- How to do ????????
employee = new Employee();
employee.id(1);
employee.name("Thirumal");
employee.mobile("+91-8973-697-871");
repository.save(employee);
}
How to check the member of objects
are empty/NULL
?
Solution
Just add that isEmpty
method to Employee
class and implement it there, or use a null object pattern instead of doing new Employee()
.
As to what you are actually trying to do in your code, I suggest to do it like that instead:
Employee employee = repository.getEmployee(id).orElseGet(() -> {
Employee emp = new Employee();
emp.id(1);
emp.name("Thirumal");
emp.mobile("+91-8973-697-871");
return repository.save(emp);
});
Answered By - Shadov
Answer Checked By - David Marino (JavaFixing Volunteer)