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