How to Convert a Java Object into an Optional with Example


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!");
        }
    }
}

tl;dr: Use Optional.ofNullable(yourObject) to wrap your object into an Optional.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap