public class Employee {
private int employeeId;
private String firstName;
private String lastName;
private double salary;
public Employee(int employeeId, String firstName, String lastName, double salary) {
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Say you have an Object of class Employee and you want to convert it into a type Optional, then follow the below code.
import java.util.Optional;
public class ObjectToOptionalExample {
public static void main(String[] args) {
Employee employee = new Employee(1,"Sam","Page",200000);
Optional<Employee> optionalEmployee = Optional.ofNullable(employee);
//Checks
if (optionalEmployee.isPresent()) {
Employee resultEmployee = optionalEmployee.get();
System.out.println("Hello " + employee.getLastName());
} else {
System.out.println("Employee object is null!");
}
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!