1 /*
   2  * Copyright (c) 2012, 2018, 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.DoubleConsumer;
  28 import java.util.function.DoubleSupplier;
  29 import java.util.function.Supplier;
  30 import java.util.stream.DoubleStream;
  31 
  32 /**
  33  * A container object which may or may not contain a {@code double} value.
  34  * If a value is present, {@code isPresent()} returns {@code true}. If no
  35  * value is present, the object is considered <i>empty</i> and
  36  * {@code isPresent()} returns {@code false}.
  37  *
  38  * <p>Additional methods that depend on the presence or absence of a contained
  39  * value are provided, such as {@link #orElse(double) orElse()}
  40  * (returns a default value if no value is present) and
  41  * {@link #ifPresent(DoubleConsumer) ifPresent()} (performs
  42  * an action if a 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 OptionalDouble} may have unpredictable results and should be avoided.
  48  *
  49  * @apiNote
  50  * {@code OptionalDouble} is primarily intended for use as a method return type where
  51  * there is a clear need to represent "no result." A variable whose type is
  52  * {@code OptionalDouble} should never itself be {@code null}; it should always point
  53  * to an {@code OptionalDouble} instance.
  54  *
  55  * @since 1.8
  56  */
  57 public final class OptionalDouble {
  58     /**
  59      * Common instance for {@code empty()}.
  60      */
  61     private static final OptionalDouble EMPTY = new OptionalDouble();
  62 
  63     /**
  64      * If true then the value is present, otherwise indicates no value is present
  65      */
  66     private final boolean isPresent;
  67     private final double value;
  68 
  69     /**
  70      * Construct an empty instance.
  71      *
  72      * @implNote generally only one empty instance, {@link OptionalDouble#EMPTY},
  73      * should exist per VM.
  74      */
  75     private OptionalDouble() {
  76         this.isPresent = false;
  77         this.value = Double.NaN;
  78     }
  79 
  80     /**
  81      * Returns an empty {@code OptionalDouble} instance.  No value is present
  82      * for this {@code OptionalDouble}.
  83      *
  84      * @apiNote
  85      * Though it may be tempting to do so, avoid testing if an object is empty
  86      * by comparing with {@code ==} against instances returned by
  87      * {@code OptionalDouble.empty()}.  There is no guarantee that it is a singleton.
  88      * Instead, use {@link #isPresent()}.
  89      *
  90      *  @return an empty {@code OptionalDouble}.
  91      */
  92     public static OptionalDouble empty() {
  93         return EMPTY;
  94     }
  95 
  96     /**
  97      * Construct an instance with the described value.
  98      *
  99      * @param value the double value to describe.
 100      */
 101     private OptionalDouble(double value) {
 102         this.isPresent = true;
 103         this.value = value;
 104     }
 105 
 106     /**
 107      * Returns an {@code OptionalDouble} describing the given value.
 108      *
 109      * @param value the value to describe
 110      * @return an {@code OptionalDouble} with the value present
 111      */
 112     public static OptionalDouble of(double value) {
 113         return new OptionalDouble(value);
 114     }
 115 
 116     /**
 117      * If a value is present, returns the value, otherwise throws
 118      * {@code NoSuchElementException}.
 119      *
 120      * @apiNote
 121      * The preferred alternative to this method is {@link #orElseThrow()}.
 122      *
 123      * @return the value described by this {@code OptionalDouble}
 124      * @throws NoSuchElementException if no value is present
 125      */
 126     public double getAsDouble() {
 127         if (!isPresent) {
 128             throw new NoSuchElementException("No value present");
 129         }
 130         return value;
 131     }
 132 
 133     /**
 134      * If a value is present, returns {@code true}, otherwise {@code false}.
 135      *
 136      * @return {@code true} if a value is present, otherwise {@code false}
 137      */
 138     public boolean isPresent() {
 139         return isPresent;
 140     }
 141 
 142     /**
 143      * If a value is not present, returns {@code true}, otherwise
 144      * {@code false}.
 145      *
 146      * @return  {@code true} if a value is not present, otherwise {@code false}
 147      * @since   11
 148      */
 149     public boolean isEmpty() {
 150         return !isPresent;
 151     }
 152 
 153 
 154     /**
 155      * If a value is present, performs the given action with the value,
 156      * otherwise does nothing.
 157      *
 158      * @param action the action to be performed, if a value is present
 159      * @throws NullPointerException if value is present and the given action is
 160      *         {@code null}
 161      */
 162     public void ifPresent(DoubleConsumer action) {
 163         if (isPresent) {
 164             action.accept(value);
 165         }
 166     }
 167 
 168     /**
 169      * If a value is present, performs the given action with the value,
 170      * otherwise performs the given empty-based action.
 171      *
 172      * @param action the action to be performed, if a value is present
 173      * @param emptyAction the empty-based action to be performed, if no value is
 174      * present
 175      * @throws NullPointerException if a value is present and the given action
 176      *         is {@code null}, or no value is present and the given empty-based
 177      *         action is {@code null}.
 178      * @since 9
 179      */
 180     public void ifPresentOrElse(DoubleConsumer action, Runnable emptyAction) {
 181         if (isPresent) {
 182             action.accept(value);
 183         } else {
 184             emptyAction.run();
 185         }
 186     }
 187 
 188     /**
 189      * If a value is present, returns a sequential {@link DoubleStream}
 190      * containing only that value, otherwise returns an empty
 191      * {@code DoubleStream}.
 192      *
 193      * @apiNote
 194      * This method can be used to transform a {@code Stream} of optional doubles
 195      * to a {@code DoubleStream} of present doubles:
 196      * <pre>{@code
 197      *     Stream<OptionalDouble> os = ..
 198      *     DoubleStream s = os.flatMapToDouble(OptionalDouble::stream)
 199      * }</pre>
 200      *
 201      * @return the optional value as a {@code DoubleStream}
 202      * @since 9
 203      */
 204     public DoubleStream stream() {
 205         if (isPresent) {
 206             return DoubleStream.of(value);
 207         } else {
 208             return DoubleStream.empty();
 209         }
 210     }
 211 
 212     /**
 213      * If a value is present, returns the value, otherwise returns
 214      * {@code other}.
 215      *
 216      * @param other the value to be returned, if no value is present
 217      * @return the value, if present, otherwise {@code other}
 218      */
 219     public double orElse(double other) {
 220         return isPresent ? value : other;
 221     }
 222 
 223     /**
 224      * If a value is present, returns the value, otherwise returns the result
 225      * produced by the supplying function.
 226      *
 227      * @param supplier the supplying function that produces a value to be returned
 228      * @return the value, if present, otherwise the result produced by the
 229      *         supplying function
 230      * @throws NullPointerException if no value is present and the supplying
 231      *         function is {@code null}
 232      */
 233     public double orElseGet(DoubleSupplier supplier) {
 234         return isPresent ? value : supplier.getAsDouble();
 235     }
 236 
 237     /**
 238      * If a value is present, returns the value, otherwise throws
 239      * {@code NoSuchElementException}.
 240      *
 241      * @return the value described by this {@code OptionalDouble}
 242      * @throws NoSuchElementException if no value is present
 243      * @since 10
 244      */
 245     public double orElseThrow() {
 246         if (!isPresent) {
 247             throw new NoSuchElementException("No value present");
 248         }
 249         return value;
 250     }
 251 
 252     /**
 253      * If a value is present, returns the value, otherwise throws an exception
 254      * produced by the exception supplying function.
 255      *
 256      * @apiNote
 257      * A method reference to the exception constructor with an empty argument
 258      * list can be used as the supplier. For example,
 259      * {@code IllegalStateException::new}
 260      *
 261      * @param <X> Type of the exception to be thrown
 262      * @param exceptionSupplier the supplying function that produces an
 263      *        exception to be thrown
 264      * @return the value, if present
 265      * @throws X if no value is present
 266      * @throws NullPointerException if no value is present and the exception
 267      *         supplying function is {@code null}
 268      */
 269     public<X extends Throwable> double orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
 270         if (isPresent) {
 271             return value;
 272         } else {
 273             throw exceptionSupplier.get();
 274         }
 275     }
 276 
 277     /**
 278      * Indicates whether some other object is "equal to" this
 279      * {@code OptionalDouble}. The other object is considered equal if:
 280      * <ul>
 281      * <li>it is also an {@code OptionalDouble} and;
 282      * <li>both instances have no value present or;
 283      * <li>the present values are "equal to" each other via
 284      * {@code Double.compare() == 0}.
 285      * </ul>
 286      *
 287      * @param obj an object to be tested for equality
 288      * @return {@code true} if the other object is "equal to" this object
 289      *         otherwise {@code false}
 290      */
 291     @Override
 292     public boolean equals(Object obj) {
 293         if (this == obj) {
 294             return true;
 295         }
 296 
 297         if (!(obj instanceof OptionalDouble)) {
 298             return false;
 299         }
 300 
 301         OptionalDouble other = (OptionalDouble) obj;
 302         return (isPresent && other.isPresent)
 303                ? Double.compare(value, other.value) == 0
 304                : isPresent == other.isPresent;
 305     }
 306 
 307     /**
 308      * Returns the hash code of the value, if present, otherwise {@code 0}
 309      * (zero) if no value is present.
 310      *
 311      * @return hash code value of the present value or {@code 0} if no value is
 312      *         present
 313      */
 314     @Override
 315     public int hashCode() {
 316         return isPresent ? Double.hashCode(value) : 0;
 317     }
 318 
 319     /**
 320      * Returns a non-empty string representation of this {@code OptionalDouble}
 321      * suitable for debugging.  The exact presentation format is unspecified and
 322      * may vary between implementations and versions.
 323      *
 324      * @implSpec
 325      * If a value is present the result must include its string representation
 326      * in the result.  Empty and present {@code OptionalDouble}s must be
 327      * unambiguously differentiable.
 328      *
 329      * @return the string representation of this instance
 330      */
 331     @Override
 332     public String toString() {
 333         return isPresent
 334                 ? String.format("OptionalDouble[%s]", value)
 335                 : "OptionalDouble.empty";
 336     }
 337 }