Optional Value
Description
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.
OptionalInt, OptionalLong, and OptionalDouble deal with optional primitive values.
- getAsInt() method from OptionalInt class returns int value.
- getAsLong() method from OptionalLong class return long value.
- getAsDouble() method from OptionalDouble class return double value.
The getters for primitive optional classes also throw a NoSuchElementException when they are empty.
Example
The following code shows how to use the OptionalInt class:
import java.util.OptionalInt;
/*w w w . j a v a 2 s. com*/
public class Main {
public static void main(String[] args) {
OptionalInt number = OptionalInt.of(2);
if (number.isPresent()) {
int value = number.getAsInt();
System.out.println("Number is " + value);
} else {
System.out.println("Number is absent.");
}
}
}
The code above generates the following result.