1 /*
  2  * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 package java.util;
 26 
 27 import java.util.function.Consumer;
 28 import java.util.function.Function;
 29 import java.util.function.Predicate;
 30 import java.util.function.Supplier;
 31 import java.util.stream.Stream;
 32 
 33 /**
 34  * A container object which may or may not contain a non-{@code null} value.
 35  * If a value is present, {@code isPresent()} returns {@code true}. If no
 36  * value is present, the object is considered <i>empty</i> and
 37  * {@code isPresent()} returns {@code false}.
 38  *
 39  * <p>Additional methods that depend on the presence or absence of a contained
 40  * value are provided, such as {@link #orElse(Object) orElse()}
 41  * (returns a default value if no value is present) and
 42  * {@link #ifPresent(Consumer) ifPresent()} (performs an
 43  * action if a value is present).
 44  *
 45  * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
 46  * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
 47  * as interchangeable and should not use instances for synchronization, mutexes, or
 48  * with {@linkplain java.lang.ref.Reference object references}.
 49  *
 50  * <div class="preview-block">
 51  *      <div class="preview-comment">
 52  *          When preview features are enabled, {@code Optional} is a {@linkplain Class#isValue value class}.
 53  *          Use of value class instances for synchronization, mutexes, or with
 54  *          {@linkplain java.lang.ref.Reference object references} result in
 55  *          {@link IdentityException}.
 56  *      </div>
 57  * </div>
 58  *
 59  * @apiNote
 60  * {@code Optional} is primarily intended for use as a method return type where
 61  * there is a clear need to represent "no result," and where using {@code null}
 62  * is likely to cause errors. A variable whose type is {@code Optional} should
 63  * never itself be {@code null}; it should always point to an {@code Optional}
 64  * instance.
 65  *
 66  * @param <T> the type of value
 67  * @since 1.8
 68  */
 69 @jdk.internal.MigratedValueClass
 70 @jdk.internal.ValueBased
 71 public final class Optional<T> {
 72     /**
 73      * Common instance for {@code empty()}.
 74      */
 75     private static final Optional<?> EMPTY = new Optional<>(null);
 76 
 77     /**
 78      * If non-null, the value; if null, indicates no value is present
 79      */
 80     private final T value;
 81 
 82     /**
 83      * Returns an empty {@code Optional} instance.  No value is present for this
 84      * {@code Optional}.
 85      *
 86      * @apiNote
 87      * Though it may be tempting to do so, avoid testing if an object is empty
 88      * by comparing with {@code ==} or {@code !=} against instances returned by
 89      * {@code Optional.empty()}.  There is no guarantee that it is a singleton.
 90      * Instead, use {@link #isEmpty()} or {@link #isPresent()}.
 91      *
 92      * @param <T> The type of the non-existent value
 93      * @return an empty {@code Optional}
 94      */
 95     public static<T> Optional<T> empty() {
 96         @SuppressWarnings("unchecked")
 97         Optional<T> t = (Optional<T>) EMPTY;
 98         return t;
 99     }
100 
101     /**
102      * Constructs an instance with the described value.
103      *
104      * @param value the value to describe; it's the caller's responsibility to
105      *        ensure the value is non-{@code null} unless creating the singleton
106      *        instance returned by {@code empty()}.
107      */
108     private Optional(T value) {
109         this.value = value;
110     }
111 
112     /**
113      * Returns an {@code Optional} describing the given non-{@code null}
114      * value.
115      *
116      * @param value the value to describe, which must be non-{@code null}
117      * @param <T> the type of the value
118      * @return an {@code Optional} with the value present
119      * @throws NullPointerException if value is {@code null}
120      */
121     public static <T> Optional<T> of(T value) {
122         return new Optional<>(Objects.requireNonNull(value));
123     }
124 
125     /**
126      * Returns an {@code Optional} describing the given value, if
127      * non-{@code null}, otherwise returns an empty {@code Optional}.
128      *
129      * @param value the possibly-{@code null} value to describe
130      * @param <T> the type of the value
131      * @return an {@code Optional} with a present value if the specified value
132      *         is non-{@code null}, otherwise an empty {@code Optional}
133      */
134     @SuppressWarnings("unchecked")
135     public static <T> Optional<T> ofNullable(T value) {
136         return value == null ? (Optional<T>) EMPTY
137                              : new Optional<>(value);
138     }
139 
140     /**
141      * If a value is present, returns the value, otherwise throws
142      * {@code NoSuchElementException}.
143      *
144      * @apiNote
145      * The preferred alternative to this method is {@link #orElseThrow()}.
146      *
147      * @return the non-{@code null} value described by this {@code Optional}
148      * @throws NoSuchElementException if no value is present
149      */
150     public T get() {
151         if (value == null) {
152             throw new NoSuchElementException("No value present");
153         }
154         return value;
155     }
156 
157     /**
158      * If a value is present, returns {@code true}, otherwise {@code false}.
159      *
160      * @return {@code true} if a value is present, otherwise {@code false}
161      */
162     public boolean isPresent() {
163         return value != null;
164     }
165 
166     /**
167      * If a value is  not present, returns {@code true}, otherwise
168      * {@code false}.
169      *
170      * @return  {@code true} if a value is not present, otherwise {@code false}
171      * @since   11
172      */
173     public boolean isEmpty() {
174         return value == null;
175     }
176 
177     /**
178      * If a value is present, performs the given action with the value,
179      * otherwise does nothing.
180      *
181      * @param action the action to be performed, if a value is present
182      * @throws NullPointerException if value is present and the given action is
183      *         {@code null}
184      */
185     public void ifPresent(Consumer<? super T> action) {
186         if (value != null) {
187             action.accept(value);
188         }
189     }
190 
191     /**
192      * If a value is present, performs the given action with the value,
193      * otherwise performs the given empty-based action.
194      *
195      * @param action the action to be performed, if a value is present
196      * @param emptyAction the empty-based action to be performed, if no value is
197      *        present
198      * @throws NullPointerException if a value is present and the given action
199      *         is {@code null}, or no value is present and the given empty-based
200      *         action is {@code null}.
201      * @since 9
202      */
203     public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
204         if (value != null) {
205             action.accept(value);
206         } else {
207             emptyAction.run();
208         }
209     }
210 
211     /**
212      * If a value is present, and the value matches the given predicate,
213      * returns an {@code Optional} describing the value, otherwise returns an
214      * empty {@code Optional}.
215      *
216      * @param predicate the predicate to apply to a value, if present
217      * @return an {@code Optional} describing the value of this
218      *         {@code Optional}, if a value is present and the value matches the
219      *         given predicate, otherwise an empty {@code Optional}
220      * @throws NullPointerException if the predicate is {@code null}
221      */
222     public Optional<T> filter(Predicate<? super T> predicate) {
223         Objects.requireNonNull(predicate);
224         if (isEmpty()) {
225             return this;
226         } else {
227             return predicate.test(value) ? this : empty();
228         }
229     }
230 
231     /**
232      * If a value is present, returns an {@code Optional} describing (as if by
233      * {@link #ofNullable}) the result of applying the given mapping function to
234      * the value, otherwise returns an empty {@code Optional}.
235      *
236      * <p>If the mapping function returns a {@code null} result then this method
237      * returns an empty {@code Optional}.
238      *
239      * @apiNote
240      * This method supports post-processing on {@code Optional} values, without
241      * the need to explicitly check for a return status.  For example, the
242      * following code traverses a stream of URIs, selects one that has not
243      * yet been processed, and creates a path from that URI, returning
244      * an {@code Optional<Path>}:
245      *
246      * <pre>{@code
247      *     Optional<Path> p =
248      *         uris.stream().filter(uri -> !isProcessedYet(uri))
249      *                       .findFirst()
250      *                       .map(Paths::get);
251      * }</pre>
252      *
253      * Here, {@code findFirst} returns an {@code Optional<URI>}, and then
254      * {@code map} returns an {@code Optional<Path>} for the desired
255      * URI if one exists.
256      *
257      * @param mapper the mapping function to apply to a value, if present
258      * @param <U> The type of the value returned from the mapping function
259      * @return an {@code Optional} describing the result of applying a mapping
260      *         function to the value of this {@code Optional}, if a value is
261      *         present, otherwise an empty {@code Optional}
262      * @throws NullPointerException if the mapping function is {@code null}
263      */
264     public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
265         Objects.requireNonNull(mapper);
266         if (isEmpty()) {
267             return empty();
268         } else {
269             return Optional.ofNullable(mapper.apply(value));
270         }
271     }
272 
273     /**
274      * If a value is present, returns the result of applying the given
275      * {@code Optional}-bearing mapping function to the value, otherwise returns
276      * an empty {@code Optional}.
277      *
278      * <p>This method is similar to {@link #map(Function)}, but the mapping
279      * function is one whose result is already an {@code Optional}, and if
280      * invoked, {@code flatMap} does not wrap it within an additional
281      * {@code Optional}.
282      *
283      * @param <U> The type of value of the {@code Optional} returned by the
284      *            mapping function
285      * @param mapper the mapping function to apply to a value, if present
286      * @return the result of applying an {@code Optional}-bearing mapping
287      *         function to the value of this {@code Optional}, if a value is
288      *         present, otherwise an empty {@code Optional}
289      * @throws NullPointerException if the mapping function is {@code null} or
290      *         returns a {@code null} result
291      */
292     public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) {
293         Objects.requireNonNull(mapper);
294         if (isEmpty()) {
295             return empty();
296         } else {
297             @SuppressWarnings("unchecked")
298             Optional<U> r = (Optional<U>) mapper.apply(value);
299             return Objects.requireNonNull(r);
300         }
301     }
302 
303     /**
304      * If a value is present, returns an {@code Optional} describing the value,
305      * otherwise returns an {@code Optional} produced by the supplying function.
306      *
307      * @param supplier the supplying function that produces an {@code Optional}
308      *        to be returned
309      * @return returns an {@code Optional} describing the value of this
310      *         {@code Optional}, if a value is present, otherwise an
311      *         {@code Optional} produced by the supplying function.
312      * @throws NullPointerException if the supplying function is {@code null} or
313      *         produces a {@code null} result
314      * @since 9
315      */
316     public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) {
317         Objects.requireNonNull(supplier);
318         if (isPresent()) {
319             return this;
320         } else {
321             @SuppressWarnings("unchecked")
322             Optional<T> r = (Optional<T>) supplier.get();
323             return Objects.requireNonNull(r);
324         }
325     }
326 
327     /**
328      * If a value is present, returns a sequential {@link Stream} containing
329      * only that value, otherwise returns an empty {@code Stream}.
330      *
331      * @apiNote
332      * This method can be used to transform a {@code Stream} of optional
333      * elements to a {@code Stream} of present value elements:
334      * <pre>{@code
335      *     Stream<Optional<T>> os = ..
336      *     Stream<T> s = os.flatMap(Optional::stream)
337      * }</pre>
338      *
339      * @return the optional value as a {@code Stream}
340      * @since 9
341      */
342     public Stream<T> stream() {
343         if (isEmpty()) {
344             return Stream.empty();
345         } else {
346             return Stream.of(value);
347         }
348     }
349 
350     /**
351      * If a value is present, returns the value, otherwise returns
352      * {@code other}.
353      *
354      * @param other the value to be returned, if no value is present.
355      *        May be {@code null}.
356      * @return the value, if present, otherwise {@code other}
357      */
358     public T orElse(T other) {
359         return value != null ? value : other;
360     }
361 
362     /**
363      * If a value is present, returns the value, otherwise returns the result
364      * produced by the supplying function.
365      *
366      * @param supplier the supplying function that produces a value to be returned
367      * @return the value, if present, otherwise the result produced by the
368      *         supplying function
369      * @throws NullPointerException if no value is present and the supplying
370      *         function is {@code null}
371      */
372     public T orElseGet(Supplier<? extends T> supplier) {
373         return value != null ? value : supplier.get();
374     }
375 
376     /**
377      * If a value is present, returns the value, otherwise throws
378      * {@code NoSuchElementException}.
379      *
380      * @return the non-{@code null} value described by this {@code Optional}
381      * @throws NoSuchElementException if no value is present
382      * @since 10
383      */
384     public T orElseThrow() {
385         if (value == null) {
386             throw new NoSuchElementException("No value present");
387         }
388         return value;
389     }
390 
391     /**
392      * If a value is present, returns the value, otherwise throws an exception
393      * produced by the exception supplying function.
394      *
395      * @apiNote
396      * A method reference to the exception constructor with an empty argument
397      * list can be used as the supplier. For example,
398      * {@code IllegalStateException::new}
399      *
400      * @param <X> Type of the exception to be thrown
401      * @param exceptionSupplier the supplying function that produces an
402      *        exception to be thrown
403      * @return the value, if present
404      * @throws X if no value is present
405      * @throws NullPointerException if no value is present and the exception
406      *          supplying function is {@code null}
407      */
408     public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
409         if (value != null) {
410             return value;
411         } else {
412             throw exceptionSupplier.get();
413         }
414     }
415 
416     /**
417      * Indicates whether some other object is "equal to" this {@code Optional}.
418      * The other object is considered equal if:
419      * <ul>
420      * <li>it is also an {@code Optional} and;
421      * <li>both instances have no value present or;
422      * <li>the present values are "equal to" each other via {@code equals()}.
423      * </ul>
424      *
425      * @param obj an object to be tested for equality
426      * @return {@code true} if the other object is "equal to" this object
427      *         otherwise {@code false}
428      */
429     @Override
430     public boolean equals(Object obj) {
431         if (this == obj) {
432             return true;
433         }
434 
435         return obj instanceof Optional<?> other
436                 && Objects.equals(value, other.value);
437     }
438 
439     /**
440      * Returns the hash code of the value, if present, otherwise {@code 0}
441      * (zero) if no value is present.
442      *
443      * @return hash code value of the present value or {@code 0} if no value is
444      *         present
445      */
446     @Override
447     public int hashCode() {
448         return Objects.hashCode(value);
449     }
450 
451     /**
452      * Returns a non-empty string representation of this {@code Optional}
453      * suitable for debugging.  The exact presentation format is unspecified and
454      * may vary between implementations and versions.
455      *
456      * @implSpec
457      * If a value is present the result must include its string representation
458      * in the result.  Empty and present {@code Optional}s must be unambiguously
459      * differentiable.
460      *
461      * @return the string representation of this instance
462      */
463     @Override
464     public String toString() {
465         return value != null
466             ? ("Optional[" + value + "]")
467             : "Optional.empty";
468     }
469 }