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