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