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