• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2012, 2013, 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 
32 /**
33  * A container object which may or may not contain a non-null value.
34  * If a value is present, {@code isPresent()} will return {@code true} and
35  * {@code get()} will return the value.
36  *
37  * <p>Additional methods that depend on the presence or absence of a contained
38  * value are provided, such as {@link #orElse(java.lang.Object) orElse()}
39  * (return a default value if value not present) and
40  * {@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block
41  * of code if the value is present).
42  *
43  * @since 1.8
44  */
45 public final class Optional<T> {
46     /**
47      * Common instance for {@code empty()}.
48      */
49     private static final Optional<?> EMPTY = new Optional<>();
50 
51     /**
52      * If non-null, the value; if null, indicates no value is present
53      */
54     private final T value;
55 
56     /**
57      * Constructs an empty instance.
58      *
59      * @implNote Generally only one empty instance, {@link Optional#EMPTY},
60      * should exist per VM.
61      */
Optional()62     private Optional() {
63         this.value = null;
64     }
65 
66     /**
67      * Returns an empty {@code Optional} instance.  No value is present for this
68      * Optional.
69      *
70      * @apiNote Though it may be tempting to do so, avoid testing if an object
71      * is empty by comparing with {@code ==} against instances returned by
72      * {@code Option.empty()}. There is no guarantee that it is a singleton.
73      * Instead, use {@link #isPresent()}.
74      *
75      * @param <T> Type of the non-existent value
76      * @return an empty {@code Optional}
77      */
empty()78     public static<T> Optional<T> empty() {
79         @SuppressWarnings("unchecked")
80         Optional<T> t = (Optional<T>) EMPTY;
81         return t;
82     }
83 
84     /**
85      * Constructs an instance with the value present.
86      *
87      * @param value the non-null value to be present
88      * @throws NullPointerException if value is null
89      */
Optional(T value)90     private Optional(T value) {
91         this.value = Objects.requireNonNull(value);
92     }
93 
94     /**
95      * Returns an {@code Optional} with the specified present non-null value.
96      *
97      * @param <T> the class of the value
98      * @param value the value to be present, which must be non-null
99      * @return an {@code Optional} with the value present
100      * @throws NullPointerException if value is null
101      */
of(T value)102     public static <T> Optional<T> of(T value) {
103         return new Optional<>(value);
104     }
105 
106     /**
107      * Returns an {@code Optional} describing the specified value, if non-null,
108      * otherwise returns an empty {@code Optional}.
109      *
110      * @param <T> the class of the value
111      * @param value the possibly-null value to describe
112      * @return an {@code Optional} with a present value if the specified value
113      * is non-null, otherwise an empty {@code Optional}
114      */
ofNullable(T value)115     public static <T> Optional<T> ofNullable(T value) {
116         return value == null ? empty() : of(value);
117     }
118 
119     /**
120      * If a value is present in this {@code Optional}, returns the value,
121      * otherwise throws {@code NoSuchElementException}.
122      *
123      * @return the non-null value held by this {@code Optional}
124      * @throws NoSuchElementException if there is no value present
125      *
126      * @see Optional#isPresent()
127      */
get()128     public T get() {
129         if (value == null) {
130             throw new NoSuchElementException("No value present");
131         }
132         return value;
133     }
134 
135     /**
136      * Return {@code true} if there is a value present, otherwise {@code false}.
137      *
138      * @return {@code true} if there is a value present, otherwise {@code false}
139      */
isPresent()140     public boolean isPresent() {
141         return value != null;
142     }
143 
144     /**
145      * If a value is present, invoke the specified consumer with the value,
146      * otherwise do nothing.
147      *
148      * @param consumer block to be executed if a value is present
149      * @throws NullPointerException if value is present and {@code consumer} is
150      * null
151      */
ifPresent(Consumer<? super T> consumer)152     public void ifPresent(Consumer<? super T> consumer) {
153         if (value != null)
154             consumer.accept(value);
155     }
156 
157     /**
158      * If a value is present, and the value matches the given predicate,
159      * return an {@code Optional} describing the value, otherwise return an
160      * empty {@code Optional}.
161      *
162      * @param predicate a predicate to apply to the value, if present
163      * @return an {@code Optional} describing the value of this {@code Optional}
164      * if a value is present and the value matches the given predicate,
165      * otherwise an empty {@code Optional}
166      * @throws NullPointerException if the predicate is null
167      */
filter(Predicate<? super T> predicate)168     public Optional<T> filter(Predicate<? super T> predicate) {
169         Objects.requireNonNull(predicate);
170         if (!isPresent())
171             return this;
172         else
173             return predicate.test(value) ? this : empty();
174     }
175 
176     /**
177      * If a value is present, apply the provided mapping function to it,
178      * and if the result is non-null, return an {@code Optional} describing the
179      * result.  Otherwise return an empty {@code Optional}.
180      *
181      * @apiNote This method supports post-processing on optional values, without
182      * the need to explicitly check for a return status.  For example, the
183      * following code traverses a stream of file names, selects one that has
184      * not yet been processed, and then opens that file, returning an
185      * {@code Optional<FileInputStream>}:
186      *
187      * <pre>{@code
188      *     Optional<FileInputStream> fis =
189      *         names.stream().filter(name -> !isProcessedYet(name))
190      *                       .findFirst()
191      *                       .map(name -> new FileInputStream(name));
192      * }</pre>
193      *
194      * Here, {@code findFirst} returns an {@code Optional<String>}, and then
195      * {@code map} returns an {@code Optional<FileInputStream>} for the desired
196      * file if one exists.
197      *
198      * @param <U> The type of the result of the mapping function
199      * @param mapper a mapping function to apply to the value, if present
200      * @return an {@code Optional} describing the result of applying a mapping
201      * function to the value of this {@code Optional}, if a value is present,
202      * otherwise an empty {@code Optional}
203      * @throws NullPointerException if the mapping function is null
204      */
map(Function<? super T, ? extends U> mapper)205     public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
206         Objects.requireNonNull(mapper);
207         if (!isPresent())
208             return empty();
209         else {
210             return Optional.ofNullable(mapper.apply(value));
211         }
212     }
213 
214     /**
215      * If a value is present, apply the provided {@code Optional}-bearing
216      * mapping function to it, return that result, otherwise return an empty
217      * {@code Optional}.  This method is similar to {@link #map(Function)},
218      * but the provided mapper is one whose result is already an {@code Optional},
219      * and if invoked, {@code flatMap} does not wrap it with an additional
220      * {@code Optional}.
221      *
222      * @param <U> The type parameter to the {@code Optional} returned by
223      * @param mapper a mapping function to apply to the value, if present
224      *           the mapping function
225      * @return the result of applying an {@code Optional}-bearing mapping
226      * function to the value of this {@code Optional}, if a value is present,
227      * otherwise an empty {@code Optional}
228      * @throws NullPointerException if the mapping function is null or returns
229      * a null result
230      */
flatMap(Function<? super T, Optional<U>> mapper)231     public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
232         Objects.requireNonNull(mapper);
233         if (!isPresent())
234             return empty();
235         else {
236             return Objects.requireNonNull(mapper.apply(value));
237         }
238     }
239 
240     /**
241      * Return the value if present, otherwise return {@code other}.
242      *
243      * @param other the value to be returned if there is no value present, may
244      * be null
245      * @return the value, if present, otherwise {@code other}
246      */
orElse(T other)247     public T orElse(T other) {
248         return value != null ? value : other;
249     }
250 
251     /**
252      * Return the value if present, otherwise invoke {@code other} and return
253      * the result of that invocation.
254      *
255      * @param other a {@code Supplier} whose result is returned if no value
256      * is present
257      * @return the value if present otherwise the result of {@code other.get()}
258      * @throws NullPointerException if value is not present and {@code other} is
259      * null
260      */
orElseGet(Supplier<? extends T> other)261     public T orElseGet(Supplier<? extends T> other) {
262         return value != null ? value : other.get();
263     }
264 
265     /**
266      * Return the contained value, if present, otherwise throw an exception
267      * to be created by the provided supplier.
268      *
269      * @apiNote A method reference to the exception constructor with an empty
270      * argument list can be used as the supplier. For example,
271      * {@code IllegalStateException::new}
272      *
273      * @param <X> Type of the exception to be thrown
274      * @param exceptionSupplier The supplier which will return the exception to
275      * be thrown
276      * @return the present value
277      * @throws X if there is no value present
278      * @throws NullPointerException if no value is present and
279      * {@code exceptionSupplier} is null
280      */
orElseThrow(Supplier<? extends X> exceptionSupplier)281     public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
282         if (value != null) {
283             return value;
284         } else {
285             throw exceptionSupplier.get();
286         }
287     }
288 
289     /**
290      * Indicates whether some other object is "equal to" this Optional. The
291      * other object is considered equal if:
292      * <ul>
293      * <li>it is also an {@code Optional} and;
294      * <li>both instances have no value present or;
295      * <li>the present values are "equal to" each other via {@code equals()}.
296      * </ul>
297      *
298      * @param obj an object to be tested for equality
299      * @return {code true} if the other object is "equal to" this object
300      * otherwise {@code false}
301      */
302     @Override
equals(Object obj)303     public boolean equals(Object obj) {
304         if (this == obj) {
305             return true;
306         }
307 
308         if (!(obj instanceof Optional)) {
309             return false;
310         }
311 
312         Optional<?> other = (Optional<?>) obj;
313         return Objects.equals(value, other.value);
314     }
315 
316     /**
317      * Returns the hash code value of the present value, if any, or 0 (zero) if
318      * no value is present.
319      *
320      * @return hash code value of the present value or 0 if no value is present
321      */
322     @Override
hashCode()323     public int hashCode() {
324         return Objects.hashCode(value);
325     }
326 
327     /**
328      * Returns a non-empty string representation of this Optional suitable for
329      * debugging. The exact presentation format is unspecified and may vary
330      * between implementations and versions.
331      *
332      * @implSpec If a value is present the result must include its string
333      * representation in the result. Empty and present Optionals must be
334      * unambiguously differentiable.
335      *
336      * @return the string representation of this instance
337      */
338     @Override
toString()339     public String toString() {
340         return value != null
341             ? String.format("Optional[%s]", value)
342             : "Optional.empty";
343     }
344 }
345