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.Supplier;
  29 
  30 /**
  31  * A container object which may or may not contain a non-null value.
  32  * If a value is present, {@code isPresent()} will return {@code true} and
  33  * {@code get()} will return the value.
  34  *
  35  * <p>Additional methods that depend on the presence or absence of a contained
  36  * value are provided, such as {@link #orElse(java.lang.Object) orElse()}
  37  * (return a default value if value not present) and
  38  * {@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block
  39  * of code if the value is present).
  40  *
  41  * @since 1.8
  42  */
  43 public final class Optional<T> {
  44     /**
  45      * Common instance for {@code empty()}.
  46      */
  47     private static final Optional<?> EMPTY = new Optional<>();
  48 
  49     /**
  50      * If non-null, the value; if null, indicates no value is present
  51      */
  52     private final T value;
  53 
  54     /**
  55      * Construct an empty instance.
  56      *
  57      * @implNote Generally only one empty instance, {@link Optional#EMPTY},
  58      * should exist per VM.
  59      */
  60     private Optional() {
  61         this.value = null;
  62     }
  63 
  64     /**
  65      * Returns an empty {@code Optional} instance.  No value is present for this
  66      * Optional.
  67      *
  68      * @apiNote Though it may be tempting to do so, avoid testing if an object
  69      * is empty by comparing with {@code ==} against instances returned by
  70      * {@code Option.empty()}. There is no guarantee that it is a singleton.
  71      * Instead, use {@link #isPresent()}.
  72      *
  73      * @param <T> Type of the non-existent value
  74      * @return an empty {@code Optional}
  75      */
  76     public static<T> Optional<T> empty() {
  77         @SuppressWarnings("unchecked")
  78         Optional<T> t = (Optional<T>) EMPTY;
  79         return t;
  80     }
  81 
  82     /**
  83      * Construct an instance with the value present.
  84      *
  85      * @param value the non-null value to be present
  86      */
  87     private Optional(T value) {
  88         this.value = Objects.requireNonNull(value);
  89     }
  90 
  91     /**
  92      * Return an {@code Optional} with the specified present value.
  93      *
  94      * @param value the value to be present, which must be non-null
  95      * @return an {@code Optional} with the value present
  96      */
  97     public static <T> Optional<T> of(T value) {
  98         return new Optional<>(value);
  99     }
 100 
 101     /**
 102      * If a value is present in this {@code Optional}, returns the value,
 103      * otherwise throws {@code NoSuchElementException}.
 104      *
 105      * @return the non-null value held by this {@code Optional}
 106      * @throws NoSuchElementException if there is no value present
 107      *
 108      * @see Optional#isPresent()
 109      */
 110     public T get() {
 111         if (value == null) {
 112             throw new NoSuchElementException("No value present");
 113         }
 114         return value;
 115     }
 116 
 117     /**
 118      * Return {@code true} if there is a value present, otherwise {@code false}.
 119      *
 120      * @return {@code true} if there is a value present, otherwise {@code false}
 121      */
 122     public boolean isPresent() {
 123         return value != null;
 124     }
 125 
 126     /**
 127      * Have the specified consumer accept the value if a value is present,
 128      * otherwise do nothing.
 129      *
 130      * @param consumer block to be executed if a value is present
 131      * @throws NullPointerException if value is present and {@code consumer} is
 132      * null
 133      */
 134     public void ifPresent(Consumer<? super T> consumer) {
 135         if (value != null)
 136             consumer.accept(value);
 137     }
 138 
 139     /**
 140      * Return the value if present, otherwise return {@code other}.
 141      *
 142      * @param other the value to be returned if there is no value present, may
 143      * be null
 144      * @return the value, if present, otherwise {@code other}
 145      */
 146     public T orElse(T other) {
 147         return value != null ? value : other;
 148     }
 149 
 150     /**
 151      * Return the value if present, otherwise invoke {@code other} and return
 152      * the result of that invocation.
 153      *
 154      * @param other a {@code Supplier} whose result is returned if no value
 155      * is present
 156      * @return the value if present otherwise the result of {@code other.get()}
 157      * @throws NullPointerException if value is not present and {@code other} is
 158      * null
 159      */
 160     public T orElseGet(Supplier<? extends T> other) {
 161         return value != null ? value : other.get();
 162     }
 163 
 164     /**
 165      * Return the contained value, if present, otherwise throw an exception
 166      * to be created by the provided supplier.
 167      *
 168      * @apiNote A method reference to the exception constructor with an empty
 169      * argument list can be used as the supplier. For example,
 170      * {@code IllegalStateException::new}
 171      *
 172      * @param <X> Type of the exception to be thrown
 173      * @param exceptionSupplier The supplier which will return the exception to
 174      * be thrown
 175      * @return the present value
 176      * @throws X if there is no value present
 177      * @throws NullPointerException if no value is present and
 178      * {@code exceptionSupplier} is null
 179      */
 180     public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
 181         if (value != null) {
 182             return value;
 183         } else {
 184             throw exceptionSupplier.get();
 185         }
 186     }
 187 
 188     /**
 189      * Indicates whether some other object is "equal to" this Optional. The
 190      * other object is considered equal if:
 191      * <ul>
 192      * <li>it is also an {@code Optional} and;
 193      * <li>both instances have no value present or;
 194      * <li>the present values are "equal to" each other via {@code equals()}.
 195      * </ul>
 196      *
 197      * @param obj an object to be tested for equality
 198      * @return {code true} if the other object is "equal to" this object
 199      * otherwise {@code false}
 200      */
 201     @Override
 202     public boolean equals(Object obj) {
 203         if (this == obj) {
 204             return true;
 205         }
 206 
 207         if (!(obj instanceof Optional)) {
 208             return false;
 209         }
 210 
 211         Optional other = (Optional) obj;
 212         return Objects.equals(value, other.value);
 213     }
 214 
 215     /**
 216      * Returns the hash code value of the present value, if any, or 0 (zero) if
 217      * no value is present.
 218      *
 219      * @return hash code value of the present value or 0 if no value is present
 220      */
 221     @Override
 222     public int hashCode() {
 223         return Objects.hashCode(value);
 224     }
 225 
 226     /**
 227      * Returns a non-empty string representation of this Optional suitable for
 228      * debugging. The exact presentation format is unspecified and may vary
 229      * between implementations and versions.
 230      *
 231      * @implSpec If a value is present the result must include its string
 232      * representation in the result. Empty and present Optionals must be
 233      * unambiguously differentiable.
 234      *
 235      * @return the string representation of this instance
 236      */
 237     @Override
 238     public String toString() {
 239         return value != null
 240             ? String.format("Optional[%s]", value)
 241             : "Optional.empty";
 242     }
 243 }