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()} (execute a block
  42  * of code 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, invoke the specified consumer with the value,
 152      * otherwise do nothing.
 153      *
 154      * @param consumer block to be executed if a value is present
 155      * @throws NullPointerException if value is present and {@code consumer} is
 156      * null
 157      */
 158     public void ifPresent(Consumer<? super T> consumer) {
 159         if (value != null) {
 160             consumer.accept(value);
 161         }
 162     }
 163 
 164     /**
 165      * If a value is present, and the value matches the given predicate,
 166      * return an {@code Optional} describing the value, otherwise return an
 167      * empty {@code Optional}.
 168      *
 169      * @param predicate a predicate to apply to the value, if present
 170      * @return an {@code Optional} describing the value of this {@code Optional}
 171      * if a value is present and the value matches the given predicate,
 172      * otherwise an empty {@code Optional}
 173      * @throws NullPointerException if the predicate is null
 174      */
 175     public Optional<T> filter(Predicate<? super T> predicate) {
 176         Objects.requireNonNull(predicate);
 177         if (!isPresent()) {
 178             return this;
 179         } else {
 180             return predicate.test(value) ? this : empty();
 181         }
 182     }
 183 
 184     /**
 185      * If a value is present, apply the provided mapping function to it,
 186      * and if the result is non-null, return an {@code Optional} describing the
 187      * result.  Otherwise return an empty {@code Optional}.
 188      *
 189      * @apiNote This method supports post-processing on optional values, without
 190      * the need to explicitly check for a return status.  For example, the
 191      * following code traverses a stream of file names, selects one that has
 192      * not yet been processed, and then opens that file, returning an
 193      * {@code Optional<FileInputStream>}:
 194      *
 195      * <pre>{@code
 196      *     Optional<FileInputStream> fis =
 197      *         names.stream().filter(name -> !isProcessedYet(name))
 198      *                       .findFirst()
 199      *                       .map(name -> new FileInputStream(name));
 200      * }</pre>
 201      *
 202      * Here, {@code findFirst} returns an {@code Optional<String>}, and then
 203      * {@code map} returns an {@code Optional<FileInputStream>} for the desired
 204      * file if one exists.
 205      *
 206      * @param <U> The type of the result of the mapping function
 207      * @param mapper a mapping function to apply to the value, if present
 208      * @return an {@code Optional} describing the result of applying a mapping
 209      * function to the value of this {@code Optional}, if a value is present,
 210      * otherwise an empty {@code Optional}
 211      * @throws NullPointerException if the mapping function is null
 212      */
 213     public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
 214         Objects.requireNonNull(mapper);
 215         if (!isPresent()) {
 216             return empty();
 217         } else {
 218             return Optional.ofNullable(mapper.apply(value));
 219         }
 220     }
 221 
 222     /**
 223      * If a value is present, apply the provided {@code Optional}-bearing
 224      * mapping function to it, return that result, otherwise return an empty
 225      * {@code Optional}.  This method is similar to {@link #map(Function)},
 226      * but the provided mapper is one whose result is already an {@code Optional},
 227      * and if invoked, {@code flatMap} does not wrap it with an additional
 228      * {@code Optional}.
 229      *
 230      * @param <U> The type parameter to the {@code Optional} returned by
 231      * @param mapper a mapping function to apply to the value, if present
 232      *           the mapping function
 233      * @return the result of applying an {@code Optional}-bearing mapping
 234      * function to the value of this {@code Optional}, if a value is present,
 235      * otherwise an empty {@code Optional}
 236      * @throws NullPointerException if the mapping function is null or returns
 237      * a null result
 238      */
 239     public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
 240         Objects.requireNonNull(mapper);
 241         if (!isPresent()) {
 242             return empty();
 243         } else {
 244             return Objects.requireNonNull(mapper.apply(value));
 245         }
 246     }
 247 
 248     /**
 249      * If a value is present return a sequential {@link Stream} containing only
 250      * that value, otherwise return an empty {@code Stream}.
 251      *
 252      * @apiNote This method can be used to transform a {@code Stream} of
 253      * optional elements to a {@code Stream} of present value elements:
 254      *
 255      * <pre>{@code
 256      *     Stream<Optional<T>> os = ..
 257      *     Stream<T> s = os.flatMap(Optional::stream)
 258      * }</pre>
 259      *
 260      * @return the optional value as a {@code Stream}
 261      * @since 1.9
 262      */
 263     public Stream<T> stream() {
 264         if (!isPresent()) {
 265             return Stream.empty();
 266         } else {
 267             return Stream.of(value);
 268         }
 269     }
 270 
 271     /**
 272      * Return the value if present, otherwise return {@code other}.
 273      *
 274      * @param other the value to be returned if there is no value present, may
 275      * be null
 276      * @return the value, if present, otherwise {@code other}
 277      */
 278     public T orElse(T other) {
 279         return value != null ? value : other;
 280     }
 281 
 282     /**
 283      * Return the value if present, otherwise invoke {@code other} and return
 284      * the result of that invocation.
 285      *
 286      * @param other a {@code Supplier} whose result is returned if no value
 287      * is present
 288      * @return the value if present otherwise the result of {@code other.get()}
 289      * @throws NullPointerException if value is not present and {@code other} is
 290      * null
 291      */
 292     public T orElseGet(Supplier<? extends T> other) {
 293         return value != null ? value : other.get();
 294     }
 295 
 296     /**
 297      * Return the contained value, if present, otherwise throw an exception
 298      * to be created by the provided supplier.
 299      *
 300      * @apiNote A method reference to the exception constructor with an empty
 301      * argument list can be used as the supplier. For example,
 302      * {@code IllegalStateException::new}
 303      *
 304      * @param <X> Type of the exception to be thrown
 305      * @param exceptionSupplier The supplier which will return the exception to
 306      * be thrown
 307      * @return the present value
 308      * @throws X if there is no value present
 309      * @throws NullPointerException if no value is present and
 310      * {@code exceptionSupplier} is null
 311      */
 312     public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
 313         if (value != null) {
 314             return value;
 315         } else {
 316             throw exceptionSupplier.get();
 317         }
 318     }
 319 
 320     /**
 321      * Indicates whether some other object is "equal to" this Optional. The
 322      * other object is considered equal if:
 323      * <ul>
 324      * <li>it is also an {@code Optional} and;
 325      * <li>both instances have no value present or;
 326      * <li>the present values are "equal to" each other via {@code equals()}.
 327      * </ul>
 328      *
 329      * @param obj an object to be tested for equality
 330      * @return {code true} if the other object is "equal to" this object
 331      * otherwise {@code false}
 332      */
 333     @Override
 334     public boolean equals(Object obj) {
 335         if (this == obj) {
 336             return true;
 337         }
 338 
 339         if (!(obj instanceof Optional)) {
 340             return false;
 341         }
 342 
 343         Optional<?> other = (Optional<?>) obj;
 344         return Objects.equals(value, other.value);
 345     }
 346 
 347     /**
 348      * Returns the hash code value of the present value, if any, or 0 (zero) if
 349      * no value is present.
 350      *
 351      * @return hash code value of the present value or 0 if no value is present
 352      */
 353     @Override
 354     public int hashCode() {
 355         return Objects.hashCode(value);
 356     }
 357 
 358     /**
 359      * Returns a non-empty string representation of this Optional suitable for
 360      * debugging. The exact presentation format is unspecified and may vary
 361      * between implementations and versions.
 362      *
 363      * @implSpec If a value is present the result must include its string
 364      * representation in the result. Empty and present Optionals must be
 365      * unambiguously differentiable.
 366      *
 367      * @return the string representation of this instance
 368      */
 369     @Override
 370     public String toString() {
 371         return value != null
 372             ? String.format("Optional[%s]", value)
 373             : "Optional.empty";
 374     }
 375 }