Create Optional Object
Description
The Optional<T> class provides three static factory methods to create Optional objects.
- <T> Optional<T> empty()
Returns an empty Optional.
The Optional<T> returned from this method does not contain a non-null value. - <T> Optional<T> of(T value)
Returns an Optional containing the specified value as the non-null value.
If the specified value is null, it throws a NullPointerException. - <T> Optional<T> ofNullable(T value)
Returns an Optional containing the specified value if the value is non-null.
If the specified value is null, it returns an empty Optional.
Example
The following code shows how to create Optional objects:
import java.util.Optional;
//from w ww . jav a 2 s .co m
public class Main {
public static void main(String[] args) {
Optional<String> empty = Optional.empty();
System.out.println(empty);
Optional<String> str = Optional.of("java2s.com");
System.out.println(str);
String nullableString = "";
Optional<String> str2 = Optional.of(nullableString);
System.out.println(str2);
}
}
The code above generates the following result.
Example 2
The following code prints the value in an Optional if it contains a non-null value:
import java.util.Optional;
// ww w . ja v a 2 s . c o m
public class Main {
public static void main(String[] args) {
Optional<String> str = Optional.of("java2s.com");
if (str.isPresent()) {
String value = str.get();
System.out.println("Optional contains " + value);
} else {
System.out.println("Optional is empty.");
}
}
}
The code above generates the following result.