Part 4 – Optional in Java 8

Optional in Java 8

What have we learned so far

What have we learned so far

1. Functional Interface And Default Methods In Java 8 –
PART 1 : FUNCTIONAL INTERFACE AND DEFAULT METHODS IN JAVA 8

2. Lambda Expression in Java 8
PART 2 – LAMBDA EXPRESSION IN JAVA 8

3. Method Reference in Java 8
PART 3 – METHOD REFERENCE IN JAVA 8


Why to use Optional in Java 8?

Suppose we have a class structure as below and want to get the dedicated memory of the Graphics Card, but all smartphones may not have the graphics card so there are chances of Graphics Card or Dedicated Memory objects as null.
Our class structure looks like :
Capture

Let’s go with the traditional java approach :

private static void traditionalApproach(SmartPhone smartPhone) {
 String size = "unknown";
 if(smartPhone.getGraphicsCard()!=null) {
  GraphicsCard graphicsCard = smartPhone.getGraphicsCard().get();
  if(graphicsCard != null) {
   GraphicsMemory graphicsMemory = graphicsCard.getGraphicsMemory();
   if(graphicsMemory != null && graphicsMemory.getDedicatedMemory() != null) {
    size = graphicsMemory.getDedicatedMemory();
   }
  }
 }
 System.out.println("Size : " + size + ", for Object : "+smartPhone.toString());
}

So how do we achieve this with less code and tell java to take care of handling the null pointers for us?


What is Optional in Java 8?Capture2
Java 8 introduced a new class java.util.Optional<T> which encapsulates a value. 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(). The Optional may contain an Object or an empty instance of a class or a null value.
For more methods of Optional please refer to below url – https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
With Optional :

private static void getGraphicsCardSize(Lis) {
 String size = smartPhone.getGraphicsCard() 
    .map(GraphicsCard::getGraphicsMemory) // map returns the Optional of type passed as a parameter (here its string)
    .map(GraphicsMemory::getDedicatedMemory)
    .orElse("unkonwn");
 System.out.println("Size : " + size + ", for Object : "+smartPhone.toString());
}

So this is how optional simplifies our life.


Different ways to create Optional?

1. Optional.empty() – This method will return an empty Optional object.
Optional<GraphicsCard> card = Optional.empty();
2. Optional.of() – This method will return an Optional of object passed as an argument to the of method. Returns an Optional with the specified present non-null value.
Optional<GraphicsCard> card = Optional.ofNullable(new GraphicsCard());
3. Optional. ofNullable() – Returns an Optional describing the specified value, if non-null,
otherwise returns an empty Optional
Optional<GraphicsCard> card = Optional.ofNullable(null);


What is the Difference in between Optional.of() and Optional.ofNullable() ?Optional.of() vs Optional.ofNullable() ?

Optional.of() will return the object of Optional without null check. 
Let’s look at the interns of Optional.of() method:
public static <T> Optional<T> of(T value) {
     return new Optional<>(value);
}

Optional.ofNullable() will return the object of Optional with a null check. If this method gets the null as an input then it will return the empty Optional otherwise it returns an Optional with the specified present non-null value
Let’s look at the interns of Optional.ofNullable() method:

public static <T> Optional<T> ofNullable(T value) {
     return value == null ? empty() : of(value);
}

Optional.of() should be used when you are sure that Optional will never have a null object and it will contain the object value or it will be empty but it will not be null. Optional.of() can also throw a NullPointerEception if the Optional is created with a null value.
Optional.ofNullable()- is used when there are chances that the object might be null.


Methods available in Optional

1. isPresent() – This method returns true if the object is present into an Optional object.

Optional<GraphicsCard> graphicsCard = Optional.of(new GraphicsCard());

if(graphicsCard.isPresent()) {
   System.out.println(graphicsCard.get());
}


2. get() – If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.

GraphicsCard newCard = graphicsCard.get();


3. ifPresent(Consumer<? super T> consumer) – If a value is present, invoke the specified consumer with the value, otherwise do nothing.

Optional<GraphicsCard> graphicsCard = Optional.of(new GraphicsCard());

graphicsCard.ifPresent(System.out::println);


4. orElse(T other) – Return the value if present, otherwise returns the object passed as a parameter. Internals of orElse(0 method in Java 8 Optional class.

public T orElse(T other) {

return value != null ? value : other;

}

GraphicsCard newCard = graphicsCard.orElse(new GraphicsCard());


5. orElseThrow(Supplier<? extends X> exceptionSupplier) – Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

GraphicsCard newCard = graphicsCard.orElseThrow(IllegalArgumentException::new);

We will see the rest of the methods(map, flatMap, filter) in our upcoming tutorials.

Source Code
Download source code of Java 8 features from below git repository :
java-8-features

Java 8 Features Tutorial

https://www.onlyfullstack.com/java-8-features-tutorial/


Let’s go to our next tutorial where we will discuss below points

filter(), findAny() in Java 8
In this tutorial we will understand below topics – How to use filter(), findAny() in Java 8
 – filter – Under the hood
PART 5 – FILTER(), FINDANY() IN JAVA 8