Reputation: 36432
I wanted to check if object is not null and its property is not null then call another function. I am trying to do this with Optional.
Employee is a class with a string property name. So I wanted to check if employee object is not null and name property in it is not null then call a method.
I tried some thing like below, but is this right approach, please correct me.
//Employee emp; // comes from another function
Optional.ofNullable(emp).ifPresent(obj -> Optional.ofNullable(obj.getName()).ifPresent(name ->System.out.println(name)));
Upvotes: 0
Views: 1592
Reputation: 2002
This is probably what you want
Optional.ofNullable(emp).map(Employee::getName).ifPresent(System.out::println);
Upvotes: 2