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
 47  * {@linkplain #equals(Object) equal} as interchangeable and should not
 48  * use instances for synchronization, or unpredictable behavior may
 49  * occur. For example, in a future release, synchronization may fail.
 50  *
 51  * @apiNote
 52  * {@code Optional} is primarily intended for use as a method return type where
 53  * there is a clear need to represent "no result," and where using {@code null}
 54  * is likely to cause errors. A variable whose type is {@code Optional} should
 55  * never itself be {@code null}; it should always point to an {@code Optional}
 56  * instance.
 57  *
 58  * @param <T> the type of value
 59  * @since 1.8
 60  */
 61 @jdk.internal.MigratedValueClass
 62 @jdk.internal.ValueBased
 63 public final class Optional<T> {
 64     /**
 65      * Common instance for {@code empty()}.
 66      */
 67     private static final Optional<?> EMPTY = new Optional<>(null);
 68 
 69     /**
 70      * If non-null, the value; if null, indicates no value is present
 71      */
 72     private final T value;
 73 
 74     /**
 75      * Returns an empty {@code Optional} instance.  No value is present for this
 76      * {@code Optional}.
 77      *
 78      * @apiNote
 79      * Though it may be tempting to do so, avoid testing if an object is empty
 80      * by comparing with {@code ==} or {@code !=} against instances returned by
 81      * {@code Optional.empty()}.  There is no guarantee that it is a singleton.
 82      * Instead, use {@link #isEmpty()} or {@link #isPresent()}.
 83      *
 84      * @param <T> The type of the non-existent value
 85      * @return an empty {@code Optional}
 86      */
 87     public static<T> Optional<T> empty() {
 88         @SuppressWarnings("unchecked")
 89         Optional<T> t = (Optional<T>) EMPTY;
 90         return t;
 91     }
 92 
 93     /**
 94      * Constructs an instance with the described value.
 95      *
 96      * @param value the value to describe; it's the caller's responsibility to
 97      *        ensure the value is non-{@code null} unless creating the singleton
 98      *        instance returned by {@code empty()}.
 99      */
100     private Optional(T value) {
101         this.value = value;
102     }
103 
104     /**
105      * Returns an {@code Optional} describing the given non-{@code null}
106      * value.
107      *
108      * @param value the value to describe, which must be non-{@code null}
109      * @param <T> the type of the value
110      * @return an {@code Optional} with the value present
111      * @throws NullPointerException if value is {@code null}
112      */
113     public static <T> Optional<T> of(T value) {
114         return new Optional<>(Objects.requireNonNull(value));
115     }
116 
117     /**
118      * Returns an {@code Optional} describing the given value, if
119      * non-{@code null}, otherwise returns an empty {@code Optional}.
120      *
121      * @param value the possibly-{@code null} value to describe
122      * @param <T> the type of the value
123      * @return an {@code Optional} with a present value if the specified value
124      *         is non-{@code null}, otherwise an empty {@code Optional}
125      */
126     @SuppressWarnings("unchecked")
127     public static <T> Optional<T> ofNullable(T value) {
128         return value == null ? (Optional<T>) EMPTY
129                              : new Optional<>(value);
130     }
131 
132     /**
133      * If a value is present, returns the value, otherwise throws
134      * {@code NoSuchElementException}.
135      *
136      * @apiNote
137      * The preferred alternative to this method is {@link #orElseThrow()}.
138      *
139      * @return the non-{@code null} value described by this {@code Optional}
140      * @throws NoSuchElementException if no value is present
141      */
142     public T get() {
143         if (value == null) {
144             throw new NoSuchElementException("No value present");
145         }
146         return value;
147     }
148 
149     /**
150      * If a value is present, returns {@code true}, otherwise {@code false}.
151      *
152      * @return {@code true} if a value is present, otherwise {@code false}
153      */
154     public boolean isPresent() {
155         return value != null;
156     }
157 
158     /**
159      * If a value is  not present, returns {@code true}, otherwise
160      * {@code false}.
161      *
162      * @return  {@code true} if a value is not present, otherwise {@code false}
163      * @since   11
164      */
165     public boolean isEmpty() {
166         return value == null;
167     }
168 
169     /**
170      * If a value is present, performs the given action with the value,
171      * otherwise does nothing.
172      *
173      * @param action the action to be performed, if a value is present
174      * @throws NullPointerException if value is present and the given action is
175      *         {@code null}
176      */
177     public void ifPresent(Consumer<? super T> action) {
178         if (value != null) {
179             action.accept(value);
180         }
181     }
182 
183     /**
184      * If a value is present, performs the given action with the value,
185      * otherwise performs the given empty-based action.
186      *
187      * @param action the action to be performed, if a value is present
188      * @param emptyAction the empty-based action to be performed, if no value is
189      *        present
190      * @throws NullPointerException if a value is present and the given action
191      *         is {@code null}, or no value is present and the given empty-based
192      *         action is {@code null}.
193      * @since 9
194      */
195     public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
196         if (value != null) {
197             action.accept(value);
198         } else {
199             emptyAction.run();
200         }
201     }
202 
203     /**
204      * If a value is present, and the value matches the given predicate,
205      * returns an {@code Optional} describing the value, otherwise returns an
206      * empty {@code Optional}.
207      *
208      * @param predicate the predicate to apply to a value, if present
209      * @return an {@code Optional} describing the value of this
210      *         {@code Optional}, if a value is present and the value matches the
211      *         given predicate, otherwise an empty {@code Optional}
212      * @throws NullPointerException if the predicate is {@code null}
213      */
214     public Optional<T> filter(Predicate<? super T> predicate) {
215         Objects.requireNonNull(predicate);
216         if (isEmpty()) {
217             return this;
218         } else {
219             return predicate.test(value) ? this : empty();
220         }
221     }
222 
223     /**
224      * If a value is present, returns an {@code Optional} describing (as if by
225      * {@link #ofNullable}) the result of applying the given mapping function to
226      * the value, otherwise returns an empty {@code Optional}.
227      *
228      * <p>If the mapping function returns a {@code null} result then this method
229      * returns an empty {@code Optional}.
230      *
231      * @apiNote
232      * This method supports post-processing on {@code Optional} values, without
233      * the need to explicitly check for a return status.  For example, the
234      * following code traverses a stream of URIs, selects one that has not
235      * yet been processed, and creates a path from that URI, returning
236      * an {@code Optional<Path>}:
237      *
238      * <pre>{@code
239      *     Optional<Path> p =
240      *         uris.stream().filter(uri -> !isProcessedYet(uri))
241      *                       .findFirst()
242      *                       .map(Paths::get);
243      * }</pre>
244      *
245      * Here, {@code findFirst} returns an {@code Optional<URI>}, and then
246      * {@code map} returns an {@code Optional<Path>} for the desired
247      * URI if one exists.
248      *
249      * @param mapper the mapping function to apply to a value, if present
250      * @param <U> The type of the value returned from the mapping function
251      * @return an {@code Optional} describing the result of applying a mapping
252      *         function to the value of this {@code Optional}, if a value is
253      *         present, otherwise an empty {@code Optional}
254      * @throws NullPointerException if the mapping function is {@code null}
255      */
256     public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
257         Objects.requireNonNull(mapper);
258         if (isEmpty()) {
259             return empty();
260         } else {
261             return Optional.ofNullable(mapper.apply(value));
262         }
263     }
264 
265     /**
266      * If a value is present, returns the result of applying the given
267      * {@code Optional}-bearing mapping function to the value, otherwise returns
268      * an empty {@code Optional}.
269      *
270      * <p>This method is similar to {@link #map(Function)}, but the mapping
271      * function is one whose result is already an {@code Optional}, and if
272      * invoked, {@code flatMap} does not wrap it within an additional
273      * {@code Optional}.
274      *
275      * @param <U> The type of value of the {@code Optional} returned by the
276      *            mapping function
277      * @param mapper the mapping function to apply to a value, if present
278      * @return the result of applying an {@code Optional}-bearing mapping
279      *         function to the value of this {@code Optional}, if a value is
280      *         present, otherwise an empty {@code Optional}
281      * @throws NullPointerException if the mapping function is {@code null} or
282      *         returns a {@code null} result
283      */
284     public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) {
285         Objects.requireNonNull(mapper);
286         if (isEmpty()) {
287             return empty();
288         } else {
289             @SuppressWarnings("unchecked")
290             Optional<U> r = (Optional<U>) mapper.apply(value);
291             return Objects.requireNonNull(r);
292         }
293     }
294 
295     /**
296      * If a value is present, returns an {@code Optional} describing the value,
297      * otherwise returns an {@code Optional} produced by the supplying function.
298      *
299      * @param supplier the supplying function that produces an {@code Optional}
300      *        to be returned
301      * @return returns an {@code Optional} describing the value of this
302      *         {@code Optional}, if a value is present, otherwise an
303      *         {@code Optional} produced by the supplying function.
304      * @throws NullPointerException if the supplying function is {@code null} or
305      *         produces a {@code null} result
306      * @since 9
307      */
308     public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) {
309         Objects.requireNonNull(supplier);
310         if (isPresent()) {
311             return this;
312         } else {
313             @SuppressWarnings("unchecked")
314             Optional<T> r = (Optional<T>) supplier.get();
315             return Objects.requireNonNull(r);
316         }
317     }
318 
319     /**
320      * If a value is present, returns a sequential {@link Stream} containing
321      * only that value, otherwise returns an empty {@code Stream}.
322      *
323      * @apiNote
324      * This method can be used to transform a {@code Stream} of optional
325      * elements to a {@code Stream} of present value elements:
326      * <pre>{@code
327      *     Stream<Optional<T>> os = ..
328      *     Stream<T> s = os.flatMap(Optional::stream)
329      * }</pre>
330      *
331      * @return the optional value as a {@code Stream}
332      * @since 9
333      */
334     public Stream<T> stream() {
335         if (isEmpty()) {
336             return Stream.empty();
337         } else {
338             return Stream.of(value);
339         }
340     }
341 
342     /**
343      * If a value is present, returns the value, otherwise returns
344      * {@code other}.
345      *
346      * @param other the value to be returned, if no value is present.
347      *        May be {@code null}.
348      * @return the value, if present, otherwise {@code other}
349      */
350     public T orElse(T other) {
351         return value != null ? value : other;
352     }
353 
354     /**
355      * If a value is present, returns the value, otherwise returns the result
356      * produced by the supplying function.
357      *
358      * @param supplier the supplying function that produces a value to be returned
359      * @return the value, if present, otherwise the result produced by the
360      *         supplying function
361      * @throws NullPointerException if no value is present and the supplying
362      *         function is {@code null}
363      */
364     public T orElseGet(Supplier<? extends T> supplier) {
365         return value != null ? value : supplier.get();
366     }
367 
368     /**
369      * If a value is present, returns the value, otherwise throws
370      * {@code NoSuchElementException}.
371      *
372      * @return the non-{@code null} value described by this {@code Optional}
373      * @throws NoSuchElementException if no value is present
374      * @since 10
375      */
376     public T orElseThrow() {
377         if (value == null) {
378             throw new NoSuchElementException("No value present");
379         }
380         return value;
381     }
382 
383     /**
384      * If a value is present, returns the value, otherwise throws an exception
385      * produced by the exception supplying function.
386      *
387      * @apiNote
388      * A method reference to the exception constructor with an empty argument
389      * list can be used as the supplier. For example,
390      * {@code IllegalStateException::new}
391      *
392      * @param <X> Type of the exception to be thrown
393      * @param exceptionSupplier the supplying function that produces an
394      *        exception to be thrown
395      * @return the value, if present
396      * @throws X if no value is present
397      * @throws NullPointerException if no value is present and the exception
398      *          supplying function is {@code null}
399      */
400     public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
401         if (value != null) {
402             return value;
403         } else {
404             throw exceptionSupplier.get();
405         }
406     }
407 
408     /**
409      * Indicates whether some other object is "equal to" this {@code Optional}.
410      * The other object is considered equal if:
411      * <ul>
412      * <li>it is also an {@code Optional} and;
413      * <li>both instances have no value present or;
414      * <li>the present values are "equal to" each other via {@code equals()}.
415      * </ul>
416      *
417      * @param obj an object to be tested for equality
418      * @return {@code true} if the other object is "equal to" this object
419      *         otherwise {@code false}
420      */
421     @Override
422     public boolean equals(Object obj) {
423         if (this == obj) {
424             return true;
425         }
426 
427         return obj instanceof Optional<?> other
428                 && Objects.equals(value, other.value);
429     }
430 
431     /**
432      * Returns the hash code of the value, if present, otherwise {@code 0}
433      * (zero) if no value is present.
434      *
435      * @return hash code value of the present value or {@code 0} if no value is
436      *         present
437      */
438     @Override
439     public int hashCode() {
440         return Objects.hashCode(value);
441     }
442 
443     /**
444      * Returns a non-empty string representation of this {@code Optional}
445      * suitable for debugging.  The exact presentation format is unspecified and
446      * may vary between implementations and versions.
447      *
448      * @implSpec
449      * If a value is present the result must include its string representation
450      * in the result.  Empty and present {@code Optional}s must be unambiguously
451      * differentiable.
452      *
453      * @return the string representation of this instance
454      */
455     @Override
456     public String toString() {
457         return value != null
458             ? ("Optional[" + value + "]")
459             : "Optional.empty";
460     }
461 }