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