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