In Java, an Optional object is a container object which may or may not contain a value. The Optional class is present in the java.util package.
Note: You can read more about the
Optionalclass here.
of() method of the Optional class?The of() method is used to get an instance of the Optional class with the specified not-null value.
public static <T> Optional<T> of(T value)
value: This is the value which is to be present in the Optional object. value should not be null.This method returns an Optional object with the specified value.
The below code shows how to use the of() method:
import java.util.Optional;class OptionalOfExample {public static void main(String[] args) {Optional<Integer> optional1 = Optional.of(1);System.out.println("Optional1 : " + optional1);Optional<String> optional2 = Optional.of("test");System.out.println("Optional2 : " + optional2);}}
In the above code:
Optional class.import java.util.Optional;
of() method to get an Optional object of the Integer type with value 1.Optional<Integer> optional1 = Optional.of(1);
optional1;// Optional[1]
of() method to get an Optional object of the String type with value test.Optional<String> optional2 = Optional.of("test");
optional2;// Optional[test]