Java Reference
In-Depth Information
// Create an Optional for the string "Hello"
Optional<String> str = Optional.of("Hello");
// Create an Optional with a String that may be null
String nullableString = ""; // get a string that may be null...
Optional<String> str2 = Optional.of(nullableString);
The following snippet of code prints the value in an Optional if it contains a non-null value:
// Create an Optional for the string "Hello"
Optional<String> str = Optional.of("Hello");
// Print the value in Optional
if (str.isPresent()) {
String value = str.get();
System.out.println("Optional contains " + value);
}
else {
System.out.println("Optional is empty.");
}
Optional contains Hello
You can use the ifPresent(Consumer<? super T> action) method of the Optional class to take an action on
the value contained in the Optional . If the Optional is empty, this method does not do anything. You can rewrite the
previous code to print the value in an Optional as follows:
// Create an Optional for the string "Hello"
Optional<String> str = Optional.of("Hello");
// Print the value in the Optional, if present
str.ifPresent(value -> System.out.println("Optional contains " + value));
Optional contains Hello
Note that if the Optional were empty, the code would not print anything.
The following are four methods to get the value of an Optional :
T get() : Returns the value contained in the Optional . If the Optional is empty, it throws a
NoSuchElementException .
T orElse(T defaultValue) : Returns the value contained in the Optional . If the Optional is
empty, it returns the specified defaultValue .
T orElseGet(Supplier<? extends T> defaultSupplier) : Returns the value contained
in the Optional . If the Optional is empty, it returns the value returned from the specified
defaultSupplier .
<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
throws X extends Throwable : Returns the value contained in the Optional . If the Optional
is empty, it throws the exception returned from the specified exceptionSupplier .
 
Search WWH ::




Custom Search