< prev index next >
src/java.base/share/classes/java/util/Optional.java
Print this page
rev 48216 : 8140281: add no-arg Optional.orElseThrow() as preferred alternative to get()
Reviewed-by: XXX
@@ -135,18 +135,14 @@
/**
* If a value is present, returns the value, otherwise throws
* {@code NoSuchElementException}.
*
* @apiNote
- * The methods {@link #orElse(Object) orElse} and
- * {@link #orElseGet(Supplier) orElseGet}
- * are generally preferable to this method, as they return a substitute
- * value if the value is absent, instead of throwing an exception.
+ * The preferred alternative to this method is {@link #orElseThrow()}.
*
* @return the non-{@code null} value described by this {@code Optional}
* @throws NoSuchElementException if no value is present
- * @see Optional#isPresent()
*/
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
@@ -360,10 +356,25 @@
public T orElseGet(Supplier<? extends T> supplier) {
return value != null ? value : supplier.get();
}
/**
+ * If a value is present, returns the value, otherwise throws
+ * {@code NoSuchElementException}.
+ *
+ * @return the non-{@code null} value described by this {@code Optional}
+ * @throws NoSuchElementException if no value is present
+ * @since 10
+ */
+ public T orElseThrow() {
+ if (value == null) {
+ throw new NoSuchElementException("No value present");
+ }
+ return value;
+ }
+
+ /**
* If a value is present, returns the value, otherwise throws an exception
* produced by the exception supplying function.
*
* @apiNote
* A method reference to the exception constructor with an empty argument
< prev index next >