Access value from Optional object

Introduction

Optional class was added in Java 8 release under java.util package, for more details about Optional please visit Java 8 Optional page. Optional class has a private constructor so there are different ways to creating optional object. In most of the cases we just need to Check value in Optional class, Some times just checking if the value is present or not is not enough, we need to access value from optional object.

There are different ways to access value from the Optional object.

Ways to access value from optional object

  1. Using public T get() method: 

    Public method that returns the value if the Optional is not empty.
    However we must be careful about the fact that if value is not present that is empty optional it throws NoSuchElementException. We should use this method on optional object only if we are sure that value is present and it is not empty optional.

    System.out.println(Optional.empty().get());
    Exception in thread "main" java.util.NoSuchElementException: No value present
    Optional<String> optional = Optional.of(“stacktraceguru”);
    System.out.println(optional .get());
    Output : stacktraceguru

    If value in optional can be null then we can use other methods like orElse(...) to access the value

  2. Using public T orElse(T other) method: 

    Public method that returns the value if the Optional is not empty.

    Optional optional= Optional.ofNullable("stacktraceguru");
    System.out.println(optional.orElse("Else value"));
    Output : stacktraceguru

    In above case the optional is not empty so output is value which is "stacktraceguru".

    Unlike get() method  we can specify value to be returned if empty Optional so it does not throws NoSuchElementException. This is most common and most used way to access value from optional object.

    Optional<String> optional = Optional.empty();
    System.out.println(optional.orElse("Else value"));
    Output : Else value
    Optional<String> optional = Optional.ofNullable(null);
    System.out.println(optional.orElse("Else value"));
    Output : Else value

    In both of the above case it is the empty optional so output is else argument which is "Else value"

  3. Using public T orElseGet (Supplier<? extends T> supplier) method: 

    Public method that almost similar to orElse with small difference, Unlike orElse(..) method  orElseGet  takes the supplier function as argument and this function will be executed if Optional is empty.
    This returns the value returned by supplier if Optional is empty.

    public String getDefaultValue(){

    return "Default value";

    }
    ...
    Optional<String> optional = Optional.empty();
    System.out.println(optional.orElseGet(()->getDefaultValue());
    Output : Default value

  4. Using public T orElseThrow (Supplier exceptionSupplier) method: 

    Public method which throws the exception if Optional is empty. We can use this method to throw custom exception.

    // before java 8
    public string getDateOfBirth(){ 

    Date dob= ..... // variable we need to check

    if(dob ==null)

    throw new Exception("Date not found");// if null throw exception

    else

    return dob; // else return value from variable

    }

    // using java 8
    public string getDateOfBirth(){ 

    Optional <Date> dob= ..... // optional variable

    return dob.orElseTrhow(() -> new Exception("Date not found") );

    }

Fast track reading :

      • Four (4) different methods to access value from optional object
      • public T get() : returns the value if present, if empty throws NoSuchElementException
    • We should use get() only when we are sure that the value is present
    • public T orElse(T other) : returns the value if present else return ‘other’ value. Used to specify default value for empty Optional
    • public T orElseGet( Supplier<? extends T> other) : returns the value if present else returns the value returned from other supplier function.
    • public T orElseThrow(Supplier exceptionSupplier) : returns the value if present else throws exception.

Leave a Reply

Your email address will not be published. Required fields are marked *