1 /*
2  * Copyright (c) 2012, 2018, 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 // Android-changed: removed ValueBased paragraph.
34 /**
35  * A container object which may or may not contain a non-{@code null} value.
36  * If a value is present, {@code isPresent()} returns {@code true}. If no
37  * value is present, the object is considered <i>empty</i> and
38  * {@code isPresent()} returns {@code false}.
39  *
40  * <p>Additional methods that depend on the presence or absence of a contained
41  * value are provided, such as {@link #orElse(Object) orElse()}
42  * (returns a default value if no value is present) and
43  * {@link #ifPresent(Consumer) ifPresent()} (performs an
44  * action if a value is present).
45  *
46  * @apiNote
47  * {@code Optional} is primarily intended for use as a method return type where
48  * there is a clear need to represent "no result," and where using {@code null}
49  * is likely to cause errors. A variable whose type is {@code Optional} should
50  * never itself be {@code null}; it should always point to an {@code Optional}
51  * instance.
52  *
53  * @param <T> the type of value
54  * @since 1.8
55  */
56 public final class Optional<T> {
57     /**
58      * Common instance for {@code empty()}.
59      */
60     private static final Optional<?> EMPTY = new Optional<>();
61 
62     /**
63      * If non-null, the value; if null, indicates no value is present
64      */
65     private final T value;
66 
67     /**
68      * Constructs an empty instance.
69      *
70      * @implNote Generally only one empty instance, {@link Optional#EMPTY},
71      * should exist per VM.
72      */
Optional()73     private Optional() {
74         this.value = null;
75     }
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 ==} against instances returned by
84      * {@code Optional.empty()}.  There is no guarantee that it is a singleton.
85      * Instead, use {@link #isPresent()}.
86      *
87      * @param <T> The type of the non-existent value
88      * @return an empty {@code Optional}
89      */
empty()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 non-{@code null} value to describe
100      * @throws NullPointerException if value is {@code null}
101      */
Optional(T value)102     private Optional(T value) {
103         this.value = Objects.requireNonNull(value);
104     }
105 
106     /**
107      * Returns an {@code Optional} describing the given non-{@code null}
108      * value.
109      *
110      * @param value the value to describe, which must be non-{@code null}
111      * @param <T> the type of the value
112      * @return an {@code Optional} with the value present
113      * @throws NullPointerException if value is {@code null}
114      */
of(T value)115     public static <T> Optional<T> of(T value) {
116         return new Optional<>(value);
117     }
118 
119     /**
120      * Returns an {@code Optional} describing the given value, if
121      * non-{@code null}, otherwise returns an empty {@code Optional}.
122      *
123      * @param value the possibly-{@code null} value to describe
124      * @param <T> the type of the value
125      * @return an {@code Optional} with a present value if the specified value
126      *         is non-{@code null}, otherwise an empty {@code Optional}
127      */
ofNullable(T value)128     public static <T> Optional<T> ofNullable(T value) {
129         return value == null ? empty() : of(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      */
get()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      */
isPresent()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      */
isEmpty()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      */
ifPresent(Consumer<? super T> action)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      */
ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)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      */
filter(Predicate<? super T> predicate)214     public Optional<T> filter(Predicate<? super T> predicate) {
215         Objects.requireNonNull(predicate);
216         if (!isPresent()) {
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      */
map(Function<? super T, ? extends U> mapper)256     public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
257         Objects.requireNonNull(mapper);
258         if (!isPresent()) {
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      */
flatMap(Function<? super T, ? extends Optional<? extends U>> mapper)284     public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) {
285         Objects.requireNonNull(mapper);
286         if (!isPresent()) {
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      */
or(Supplier<? extends Optional<? extends T>> supplier)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      */
stream()334     public Stream<T> stream() {
335         if (!isPresent()) {
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      */
orElse(T other)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      */
orElseGet(Supplier<? extends T> supplier)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      */
orElseThrow()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      */
orElseThrow(Supplier<? extends X> exceptionSupplier)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
equals(Object obj)422     public boolean equals(Object obj) {
423         if (this == obj) {
424             return true;
425         }
426 
427         if (!(obj instanceof Optional)) {
428             return false;
429         }
430 
431         Optional<?> other = (Optional<?>) obj;
432         return Objects.equals(value, other.value);
433     }
434 
435     /**
436      * Returns the hash code of the value, if present, otherwise {@code 0}
437      * (zero) if no value is present.
438      *
439      * @return hash code value of the present value or {@code 0} if no value is
440      *         present
441      */
442     @Override
hashCode()443     public int hashCode() {
444         return Objects.hashCode(value);
445     }
446 
447     /**
448      * Returns a non-empty string representation of this {@code Optional}
449      * suitable for debugging.  The exact presentation format is unspecified and
450      * may vary between implementations and versions.
451      *
452      * @implSpec
453      * If a value is present the result must include its string representation
454      * in the result.  Empty and present {@code Optional}s must be unambiguously
455      * differentiable.
456      *
457      * @return the string representation of this instance
458      */
459     @Override
toString()460     public String toString() {
461         return value != null
462             ? String.format("Optional[%s]", value)
463             : "Optional.empty";
464     }
465 }
466