How to use Optional in Java 8

Category : Java | Sub Category : Java 8 Features | By Runner Dev Last updated: 2020-10-01 09:23:59 Viewed : 320

Java 8 Optional

/* @since 1.8


public final class Optional<T> { }


A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).
This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.

Advantages of Java 8 Optional:

Java 8 Optional Example: 

import java.util.ArrayList;

import java.util.List;

import java.util.Optional; 

public class Java8OptionalEx {

     public static void main(String args[]) {

           // Basic Optional orElse method

    Optional<String> animal = Optional.of("Dog");          

    Optional<String> emptyStr = Optional.empty();

System.out.println("animal.orElse " + animal.orElse(" "));//Dog  

System.out.println("emptyStr.orElse " + emptyStr.orElse("N/A"));//N/A 

System.out.println("animal.orElseGet "+animal.orElseGet(()->""));//Dog

System.out.println("emptyStr.orElseGet "+emptyStr.orElseGet(() -> "N/A"));//N/A

   // Optional isPresent and ifPresent

if (animal.isPresent()) {

   System.out.println("animal.isPresent() " + "Animal is present."); 

else {         

System.out.println("Animal not present.");     


/** ifPresent */
animal.ifPresent(a -> System.out.println("animal.ifPresent " + " animal Option available."));

// if condition failed

emptyStr.ifPresent(a -> System.out.println("emptyStr.ifPresent " + "emptyStrOption available."));

 /**Returns an Optional with the specified present non-null value. **/

Address address = new Address("1-22,Srinagar, "Hyder","India",56001);

Employee emp1 = new Employee("Ram", Optional.of(address), 111);

Employee emp1 = new Employee("Meera", Optional.empty(), 999);

Employee emp2 = new Employee("Shyam", Optional.empty(), 555);

List<Employee> people = new ArrayList<>();



           people.add(emp2); -> { System.out.printf("%s stay %s %n", p.address().orElse(Address.EMPTY_ADDRESS));



Pojo Class 1:  

 class Employee {

            private String name; //setters and getters

            private Optional<Address> address; //setters and getters

            private int phone; //setters and getters


public Employee(String name, Optional<Address> addressint phone) {

if (name == null) {

    throw new IllegalArgumentException("Null value for empName is not allowed");


               = name;

                        this.address = address;

               = phone;




Pojo class 2:  


 class Address {

            public static final Address EMPTY_ADDRESS = new Address("""""", 0);

            private final String addreLine; //setters and getters

            private final String city; //setters and getters

            private final String country//setters and getters

            private final int zipcode;


public Address(String addreLine, String city, String countryint zipcode) {

                        this.addreLine = addreLine;

               = city;

               = country;

                        this.zipcode = zipcode;





    animal.orElse Dog

    emptyStr.orElse N/A

    animal.orElseGet Dog

    emptyStr.orElseGet N/A

    Ram stay Address{addreLine=1-22 ,Srinagar, city=Hyder, country=India, zipcode=56001} 

    Meera stay Address{addreLine=, city=, country=, zipcode=0} 

    Shyam stay Address{addreLine=, city=, country=, zipcode=0} 

    animal.isPresent() Animal is present.

    animal.ifPresent  animal Option available.

Related Articles

Leave a Comment:
at 2022-04-17 13:16:28
[url=]where can i buy cialis on line[/url] Sdtpzn Precio De Cialis Con Receta <a href="">Cialis</a> Tsbjzw Levitra Pour Femmes - is there a generic cialis available Lryspk buy generic cialis uk