Wednesday, 29 June 2016

Optional Class Example in Java 8


In the previous article I explained about Collectors in Java 8. Now we will move on to another class that is introduced in Java 8 called Optional.

Optional is a new class introduced in Java 8 to address problems associated with NullPointerExceptions.
The Optional object in Java 8 is used to hold a SINGLE value which as the name suggests, is optional, meaning it
has two options, that is it can be null or not-null.
Which means that it is a container object which may or may not contain a NULL value.


Some of them are Explained in details below:
Optional.isPresent()
Optional.get()
Optional.orElse()
Optional.orElseGet()
Optional.orElseThrow()
Optional.filter()
Optional.of()
Optional.ofNullable()
Optional.empty()


Consider the code sample.
We have two separate streams. Stream1 is having valid data while Stream2 is empty stream.

Stream<String> items1=Stream.of("findFirst","Example","Stream","Java8");
Stream<String> items2=Stream.of();
  
Optional<String> op1 = items1.findFirst();   
Optional<String> op2 = items2.findFirst();  


The Optional.isPresent() method


The ispresent() method of the optional object returns true if there is a value present,
otherwise it returns false.

System.out.println(op1.isPresent()); //true
System.out.println(op2.isPresent()); //false



The Optional.get() method

The get() method of the Optional object returns the value if a value is present in this Optional
object, otherwise throws NoSuchElementException.

System.out.println(op1.get()); //findFirst
System.out.println(op2.get()); //java.util.NoSuchElementException: No value present



The Optional.orElse() method


If a value is present in this optional then it is returned else it returns the replacement.
Since the 1st optional object has a value thus the value is returned.
The second optional does not have a value and thus the replacement "Hello" is returned.

System.out.println(op1.orElse("Hello"));  // findFirst
System.out.println(op2.orElse("Hello"));  // Hello



The Optional.orElseGet() method

Return the value if present, otherwise invoke supplied object and return the result of that invocation.
Here in the first case op1 has value hence the value is returned.
In the case of op2, there is no value and it will call the supplier.get() method by default.

Supplier<String> supplier=new Supplier<String>() {

   @Override
   public String get() {
    
    return "This is a replacement";
   }
  };
System.out.println(op1.orElseGet(supplier));  // findFirst
System.out.println(op2.orElseGet(supplier));  // This is a replacement



The Optional.orElseThrow() method

The orElseThrow() method of the Optional class returns the contained value, if present,
otherwise throw an exception to be created by the provided supplier.

System.out.println(op1.orElseThrow(NullPointerException::new));  // findFirst
System.out.println(op2.orElseThrow(NullPointerException::new));  // java.lang.NullPointerException



The Optional.filter() method

The filter() method in the Optional class is used to filter the data based on a given condition.
If this condition is met then it returns an Optional object defining its value.
Else if the filter condition is not met it will return a Optional.empty object.

System.out.println(op1);                                   //Optional[findFirst]
System.out.println(op1.filter(x -> x.contains("First")));  // Optional[findFirst]
System.out.println(op1.filter(x -> x.contains("Second"))); // Optional.empty



The Optional.of() method

The of() method of the optional class returns an Optional with the specified present non-null value.
It is to be noted here that the value supplied must not be NULL in any situation else we will get a NullPointerException in those cases. If we have situations where the supplied value
may be null then we must use ofNullable() instead.

Optional<String> op1 = Optional.of("Hello");
System.out.println(op1.get());  // Hello



The Optional.ofNullable() method

The ofznullable() method in Optional class returns an Optional describing the specified value,
if non-null, otherwise returns an empty Optional.Unlike of() it accepts NULL values.
If the Null value is supplied then it returns an empty Optional object.

Optional<String> op1 = Optional.ofNullable("Hello");
System.out.println(op1);  // Optional[Hello]

  
Optional<String> op2 = Optional.ofNullable(null);
System.out.println(op2);  // Optional.empty



The Optional.empty() method

The empty() method of the Optional class returns an empty Optional instance.
No value is present for this Optional.
It makes the Optional drop its value and makes it empty.

Optional<String> op1 = Optional.ofNullable("Hello");
System.out.println(op1);  // Optional[Hello]
  
Optional<String> op2 = op1.empty();
System.out.println(op2);  // Optional.empty



In conclusion the Optional is 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.

No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.