Lolly
Lolly

Reputation: 36432

Java Optional check for object and its property

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

Answers (1)

Gavin Haynes
Gavin Haynes

Reputation: 2002

This is probably what you want

Optional.ofNullable(emp).map(Employee::getName).ifPresent(System.out::println);

Upvotes: 2

Related Questions