Skip to main content
Optional is a container object which is used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.

Class Declaration

Following is the declaration for java.util.Optional<T> class −
public final class Optional<T>
extends Object

Class Method

S. No.Method & Description
1static <T> Optional<T> empty()
Returns an empty Optional instance.
2boolean equals(Object obj)
Indicates whether some other object is "equal to" this Optional.
3Optional<T> filter(Predicate<? super <T> predicate)
If a value is present and the value matches a given predicate, it returns an Optional describing the value, otherwise returns an empty Optional.
4<U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper)
If a value is present, it applies the provided Optional-bearing mapping function to it, returns that result, otherwise returns an empty Optional.
5T get()
If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
6int hashCode()
Returns the hash code value of the present value, if any, or 0 (zero) if no value is present.
7void ifPresent(Consumer<? super T> consumer)
If a value is present, it invokes the specified consumer with the value, otherwise does nothing.
8boolean isPresent()
Returns true if there is a value present, otherwise false.
9<U>Optional<U> map(Function<? super T,? extends U> mapper)
If a value is present, applies the provided mapping function to it, and if the result is non-null, returns an Optional describing the result.
10static <T> Optional<T> of(T value)
Returns an Optional with the specified present non-null value.
11static <T> Optional<T> ofNullable(T value)
Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
12T orElse(T other)
Returns the value if present, otherwise returns other.
13T orElseGet(Supplier<? extends T> other)
Returns the value if present, otherwise invokes other and returns the result of that invocation.
14<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
Returns the contained value, if present, otherwise throws an exception to be created by the provided supplier.
15String toString()
Returns a non-empty string representation of this Optional suitable for debugging.
Note − This class inherits methods from the java.lang.Object class.

Optional Example

To understand how Optional is used in practice, let us see the following example. Write the following program, execute and verify result to get more insight of it.

Java8Tester.java

import java.util.Optional;

public class Java8Tester {
   public static void main(String args[]){
   
      Java8Tester java8Tester = new Java8Tester();
      Integer value1 = null;
      Integer value2 = new Integer(10);
  
      //Optional.ofNullable - allows passed parameter to be null.
      Optional<Integer> a = Optional.ofNullable(value1);
  
      //Optional.of - throws NullPointerException if passed parameter is null
      Optional<Integer> b = Optional.of(value2);
      System.out.println(java8Tester.sum(a,b));
   }
 
   public Integer sum(Optional<Integer> a, Optional<Integer> b){
 
      //Optional.isPresent - checks the value is present or not
  
      System.out.println("First parameter is present: " + a.isPresent());
      System.out.println("Second parameter is present: " + b.isPresent());
  
      //Optional.orElse - returns the value if present otherwise returns
      //the default value passed.
      Integer value1 = a.orElse(new Integer(0));
  
      //Optional.get - gets the value, value should be present
      Integer value2 = b.get();
      return value1 + value2;
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
First parameter is present: false
Second parameter is present: true
10

Comments

Popular posts from this blog

The Windows Firewall with Advanced Security is a firewall that runs on the Windows Server 2012 and is turned on by default. The Firewall settings within Windows Server 2012 are managed from within the  Windows Firewall Microsoft Management Console . To set Firewall settings perform the following steps − Step 1  − Click on the Server Manager from the task bar → Click the Tools menu and select Windows Firewall with Advanced Security. Step 2  − To see the current configuration settings by selecting  Windows Firewall Properties  from the MMC. This  allows access to modify the settings  for each of the three firewall profiles, which are –  Domain, Private and Public  and IPsec settings. Step 3  − Applying custom rules, which will include the following two steps − Select either  Inbound Rules  or  Outbound Rules  under  Windows Firewall with Advanced Security  on the left side of the management console...
In this chapter, we will see how to enable remote desktop application. It is important because this enables us to work remotely on the server. To do this, we have the following two options. For the first option, we have to follow the steps given below. Step 1  − Go to Start → right click “This PC” → Properties. Step 2  − On Left side click “Remote Setting”. Step 3  − Check radio button “Allow Remote connection to this computer” and Check box “Allow connection only from computers running Remote Desktop with Network Level Authentication (recommended)” → click “Select Users”. Step 4  − Click Add. Step 5  − Type user that you want to allow access. In my case, it is administrator → click OK. For the  second option , we need to follow the steps given below. Step 1  − Click on “Server Manage” → Local Server → click on “Enable” or Disable, if it is Disabled.
In this chapter, we will see how to configure WSUS and tune it. The following steps should be followed for configuring it. Step 1  − When you open it for the first time, you should do it by going to “Server Manager” → Tools → Windows Server Update Services, then a Configuration wizard will be opened and then click → Next. Step 2  − Click “Start Connecting” → Wait until the green bar is full and then → Next. Step 3  − Check the box for which the updates want to be taken, I did for English and then → Next. Step 4  − Check the box for all the products which you want to update. It is just for Microsoft products and it is recommended to include all the products related to Microsoft and then → Next. Step 5  − Choose the classification updated to be downloaded, if you have a very good internet speed, then check all the boxes, otherwise just check “Critical Updates”. Step 6  − Now we should schedule the updates which I will recommend to do it a...