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}. 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 present, performs the given action with the value, 164 * otherwise does nothing. 165 * 166 * @param action the action to be performed, if a value is present 167 * @throws NullPointerException if value is present and the given action is 168 * {@code null} 169 */ 170 public void ifPresent(Consumer<? super T> action) { 171 if (value != null) { 172 action.accept(value); 173 } 174 } 175 176 /** 177 * If a value is present, performs the given action with the value, 178 * otherwise performs the given empty-based action. 179 * 180 * @param action the action to be performed, if a value is present 181 * @param emptyAction the empty-based action to be performed, if no value is 182 * present 183 * @throws NullPointerException if a value is present and the given action 184 * is {@code null}, or no value is present and the given empty-based 185 * action is {@code null}. 186 * @since 9 187 */ 188 public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) { 189 if (value != null) { 190 action.accept(value); 191 } else { 192 emptyAction.run(); 193 } 194 } 195 196 /** 197 * If a value is present, and the value matches the given predicate, 198 * returns an {@code Optional} describing the value, otherwise returns an 199 * empty {@code Optional}. 200 * 201 * @param predicate the predicate to apply to a value, if present 202 * @return an {@code Optional} describing the value of this 203 * {@code Optional}, if a value is present and the value matches the 204 * given predicate, otherwise an empty {@code Optional} 205 * @throws NullPointerException if the predicate is {@code null} 206 */ 207 public Optional<T> filter(Predicate<? super T> predicate) { 208 Objects.requireNonNull(predicate); 209 if (!isPresent()) { 210 return this; 211 } else { 212 return predicate.test(value) ? this : empty(); 213 } 214 } 215 216 /** 217 * If a value is present, returns an {@code Optional} describing (as if by 218 * {@link #ofNullable}) the result of applying the given mapping function to 219 * the value, otherwise returns an empty {@code Optional}. 220 * 221 * <p>If the mapping function returns a {@code null} result then this method 222 * returns an empty {@code Optional}. 223 * 224 * @apiNote 225 * This method supports post-processing on {@code Optional} values, without 226 * the need to explicitly check for a return status. For example, the 227 * following code traverses a stream of URIs, selects one that has not 228 * yet been processed, and creates a path from that URI, returning 229 * an {@code Optional<Path>}: 230 * 231 * <pre>{@code 232 * Optional<Path> p = 233 * uris.stream().filter(uri -> !isProcessedYet(uri)) 234 * .findFirst() 235 * .map(Paths::get); 236 * }</pre> 237 * 238 * Here, {@code findFirst} returns an {@code Optional<URI>}, and then 239 * {@code map} returns an {@code Optional<Path>} for the desired 240 * URI if one exists. 241 * 242 * @param mapper the mapping function to apply to a value, if present 243 * @param <U> The type of the value returned from the mapping function 244 * @return an {@code Optional} describing the result of applying a mapping 245 * function to the value of this {@code Optional}, if a value is 246 * present, otherwise an empty {@code Optional} 247 * @throws NullPointerException if the mapping function is {@code null} 248 */ 249 public <U> Optional<U> map(Function<? super T, ? extends U> mapper) { 250 Objects.requireNonNull(mapper); 251 if (!isPresent()) { 252 return empty(); 253 } else { 254 return Optional.ofNullable(mapper.apply(value)); 255 } 256 } 257 258 /** 259 * If a value is present, returns the result of applying the given 260 * {@code Optional}-bearing mapping function to the value, otherwise returns 261 * an empty {@code Optional}. 262 * 263 * <p>This method is similar to {@link #map(Function)}, but the mapping 264 * function is one whose result is already an {@code Optional}, and if 265 * invoked, {@code flatMap} does not wrap it within an additional 266 * {@code Optional}. 267 * 268 * @param <U> The type of value of the {@code Optional} returned by the 269 * mapping function 270 * @param mapper the mapping function to apply to a value, if present 271 * @return the result of applying an {@code Optional}-bearing mapping 272 * function to the value of this {@code Optional}, if a value is 273 * present, otherwise an empty {@code Optional} 274 * @throws NullPointerException if the mapping function is {@code null} or 275 * returns a {@code null} result 276 */ 277 public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) { 278 Objects.requireNonNull(mapper); 279 if (!isPresent()) { 280 return empty(); 281 } else { 282 @SuppressWarnings("unchecked") 283 Optional<U> r = (Optional<U>) mapper.apply(value); 284 return Objects.requireNonNull(r); 285 } 286 } 287 288 /** 289 * If a value is present, returns an {@code Optional} describing the value, 290 * otherwise returns an {@code Optional} produced by the supplying function. 291 * 292 * @param supplier the supplying function that produces an {@code Optional} 293 * to be returned 294 * @return returns an {@code Optional} describing the value of this 295 * {@code Optional}, if a value is present, otherwise an 296 * {@code Optional} produced by the supplying function. 297 * @throws NullPointerException if the supplying function is {@code null} or 298 * produces a {@code null} result 299 * @since 9 300 */ 301 public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) { 302 Objects.requireNonNull(supplier); 303 if (isPresent()) { 304 return this; 305 } else { 306 @SuppressWarnings("unchecked") 307 Optional<T> r = (Optional<T>) supplier.get(); 308 return Objects.requireNonNull(r); 309 } 310 } 311 312 /** 313 * If a value is present, returns a sequential {@link Stream} containing 314 * only that value, otherwise returns an empty {@code Stream}. 315 * 316 * @apiNote 317 * This method can be used to transform a {@code Stream} of optional 318 * elements to a {@code Stream} of present value elements: 319 * <pre>{@code 320 * Stream<Optional<T>> os = .. 321 * Stream<T> s = os.flatMap(Optional::stream) 322 * }</pre> 323 * 324 * @return the optional value as a {@code Stream} 325 * @since 9 326 */ 327 public Stream<T> stream() { 328 if (!isPresent()) { 329 return Stream.empty(); 330 } else { 331 return Stream.of(value); 332 } 333 } 334 335 /** 336 * If a value is present, returns the value, otherwise returns 337 * {@code other}. 338 * 339 * @param other the value to be returned, if no value is present. 340 * May be {@code null}. 341 * @return the value, if present, otherwise {@code other} 342 */ 343 public T orElse(T other) { 344 return value != null ? value : other; 345 } 346 347 /** 348 * If a value is present, returns the value, otherwise returns the result 349 * produced by the supplying function. 350 * 351 * @param supplier the supplying function that produces a value to be returned 352 * @return the value, if present, otherwise the result produced by the 353 * supplying function 354 * @throws NullPointerException if no value is present and the supplying 355 * function is {@code null} 356 */ 357 public T orElseGet(Supplier<? extends T> supplier) { 358 return value != null ? value : supplier.get(); 359 } 360 361 /** 362 * If a value is present, returns the value, otherwise throws 363 * {@code NoSuchElementException}. 364 * 365 * @return the non-{@code null} value described by this {@code Optional} 366 * @throws NoSuchElementException if no value is present 367 * @since 10 368 */ 369 public T orElseThrow() { 370 if (value == null) { 371 throw new NoSuchElementException("No value present"); 372 } 373 return value; 374 } 375 376 /** 377 * If a value is present, returns the value, otherwise throws an exception 378 * produced by the exception supplying function. 379 * 380 * @apiNote 381 * A method reference to the exception constructor with an empty argument 382 * list can be used as the supplier. For example, 383 * {@code IllegalStateException::new} 384 * 385 * @param <X> Type of the exception to be thrown 386 * @param exceptionSupplier the supplying function that produces an 387 * exception to be thrown 388 * @return the value, if present 389 * @throws X if no value is present 390 * @throws NullPointerException if no value is present and the exception 391 * supplying function is {@code null} 392 */ 393 public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { 394 if (value != null) { 395 return value; 396 } else { 397 throw exceptionSupplier.get(); 398 } 399 } 400 401 /** 402 * Indicates whether some other object is "equal to" this {@code Optional}. 403 * The other object is considered equal if: 404 * <ul> 405 * <li>it is also an {@code Optional} and; 406 * <li>both instances have no value present or; 407 * <li>the present values are "equal to" each other via {@code equals()}. 408 * </ul> 409 * 410 * @param obj an object to be tested for equality 411 * @return {@code true} if the other object is "equal to" this object 412 * otherwise {@code false} 413 */ 414 @Override 415 public boolean equals(Object obj) { 416 if (this == obj) { 417 return true; 418 } 419 420 if (!(obj instanceof Optional)) { 421 return false; 422 } 423 424 Optional<?> other = (Optional<?>) obj; 425 return Objects.equals(value, other.value); 426 } 427 428 /** 429 * Returns the hash code of the value, if present, otherwise {@code 0} 430 * (zero) if no value is present. 431 * 432 * @return hash code value of the present value or {@code 0} if no value is 433 * present 434 */ 435 @Override 436 public int hashCode() { 437 return Objects.hashCode(value); 438 } 439 440 /** 441 * Returns a non-empty string representation of this {@code Optional} 442 * suitable for debugging. The exact presentation format is unspecified and 443 * may vary between implementations and versions. 444 * 445 * @implSpec 446 * If a value is present the result must include its string representation 447 * in the result. Empty and present {@code Optional}s must be unambiguously 448 * differentiable. 449 * 450 * @return the string representation of this instance 451 */ 452 @Override 453 public String toString() { 454 return value != null 455 ? String.format("Optional[%s]", value) 456 : "Optional.empty"; 457 } 458 }