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