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.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()} will return {@code true} and
  35  * {@code getAsDouble()} 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(double) orElse()}
  39  * (return a default value if value not present) and
  40  * {@link #ifPresent(java.util.function.DoubleConsumer) ifPresent()} (perform an
  41  * action if the value is present).
  42  *
  43  * <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>
  44  * class; use of identity-sensitive operations (including reference equality
  45  * ({@code ==}), identity hash code, or synchronization) on instances of
  46  * {@code OptionalDouble} may have unpredictable results and should be avoided.
  47  *
  48  * @since 1.8
  49  */
  50 public final class OptionalDouble {
  51     /**
  52      * Common instance for {@code empty()}.
  53      */
  54     private static final OptionalDouble EMPTY = new OptionalDouble();
  55 
  56     /**
  57      * If true then the value is present, otherwise indicates no value is present
  58      */
  59     private final boolean isPresent;
  60     private final double value;
  61 
  62     /**
  63      * Construct an empty instance.
  64      *
  65      * @implNote generally only one empty instance, {@link OptionalDouble#EMPTY},
  66      * should exist per VM.
  67      */
  68     private OptionalDouble() {
  69         this.isPresent = false;
  70         this.value = Double.NaN;
  71     }
  72 
  73     /**
  74      * Returns an empty {@code OptionalDouble} instance.  No value is present for this
  75      * OptionalDouble.
  76      *
  77      * @apiNote Though it may be tempting to do so, avoid testing if an object
  78      * is empty by comparing with {@code ==} against instances returned by
  79      * {@code Option.empty()}. There is no guarantee that it is a singleton.
  80      * Instead, use {@link #isPresent()}.
  81      *
  82      *  @return an empty {@code OptionalDouble}.
  83      */
  84     public static OptionalDouble empty() {
  85         return EMPTY;
  86     }
  87 
  88     /**
  89      * Construct an instance with the value present.
  90      *
  91      * @param value the double value to be present.
  92      */
  93     private OptionalDouble(double value) {
  94         this.isPresent = true;
  95         this.value = value;
  96     }
  97 
  98     /**
  99      * Return an {@code OptionalDouble} with the specified value present.
 100      *
 101      * @param value the value to be present
 102      * @return an {@code OptionalDouble} with the value present
 103      */
 104     public static OptionalDouble of(double value) {
 105         return new OptionalDouble(value);
 106     }
 107 
 108     /**
 109      * If a value is present in this {@code OptionalDouble}, returns the value,
 110      * otherwise throws {@code NoSuchElementException}.
 111      *
 112      * @return the value held by this {@code OptionalDouble}
 113      * @throws NoSuchElementException if there is no value present
 114      *
 115      * @see OptionalDouble#isPresent()
 116      */
 117     public double getAsDouble() {
 118         if (!isPresent) {
 119             throw new NoSuchElementException("No value present");
 120         }
 121         return value;
 122     }
 123 
 124     /**
 125      * Return {@code true} if there is a value present, otherwise {@code false}.
 126      *
 127      * @return {@code true} if there is a value present, otherwise {@code false}
 128      */
 129     public boolean isPresent() {
 130         return isPresent;
 131     }
 132 
 133     /**
 134      * If a value is present, perform the given action with the value,
 135      * otherwise do nothing.
 136      *
 137      * @param action the action to be performed if a value is present
 138      * @throws NullPointerException if a value is present and {@code action} is
 139      * null
 140      */
 141     public void ifPresent(DoubleConsumer action) {
 142         if (isPresent) {
 143             action.accept(value);
 144         }
 145     }
 146 
 147     /**
 148      * If a value is present, perform the given action with the value,
 149      * otherwise perform the given empty-based action.
 150      *
 151      * @param action the action to be performed if a value is present
 152      * @param emptyAction the empty-based action to be performed if a value is
 153      * not present
 154      * @throws NullPointerException if a value is present and {@code action} is
 155      * null, or a value is not present and {@code emptyAction} is null.
 156      * @since 1.9
 157      */
 158     public void ifPresentOrElse(DoubleConsumer action, Runnable emptyAction) {
 159         if (isPresent) {
 160             action.accept(value);
 161         } else {
 162             emptyAction.run();
 163         }
 164     }
 165 
 166     /**
 167      * If a value is present return a sequential {@link DoubleStream} containing
 168      * only that value, otherwise return an empty {@code DoubleStream}.
 169      *
 170      * @apiNote This method can be used to transform a {@code Stream} of
 171      * optional doubles to a {@code DoubleStream} of present doubles:
 172      *
 173      * <pre>{@code
 174      *     Stream<OptionalDouble> os = ..
 175      *     DoubleStream s = os.flatMapToDouble(OptionalDouble::stream)
 176      * }</pre>
 177      *
 178      * @return the optional value as a {@code DoubleStream}
 179      * @since 1.9
 180      */
 181     public DoubleStream stream() {
 182         if (isPresent) {
 183             return DoubleStream.of(value);
 184         } else {
 185             return DoubleStream.empty();
 186         }
 187     }
 188 
 189     /**
 190      * Return the value if present, otherwise return {@code other}.
 191      *
 192      * @param other the value to be returned if there is no value present
 193      * @return the value, if present, otherwise {@code other}
 194      */
 195     public double orElse(double other) {
 196         return isPresent ? value : other;
 197     }
 198 
 199     /**
 200      * Return the value if present, otherwise invoke {@code other} and return
 201      * the result of that invocation.
 202      *
 203      * @param other a {@code DoubleSupplier} whose result is returned if no value
 204      * is present
 205      * @return the value if present otherwise the result of {@code other.getAsDouble()}
 206      * @throws NullPointerException if value is not present and {@code other} is
 207      * null
 208      */
 209     public double orElseGet(DoubleSupplier other) {
 210         return isPresent ? value : other.getAsDouble();
 211     }
 212 
 213     /**
 214      * Return the contained value, if present, otherwise throw an exception
 215      * to be created by the provided supplier.
 216      *
 217      * @apiNote A method reference to the exception constructor with an empty
 218      * argument list can be used as the supplier. For example,
 219      * {@code IllegalStateException::new}
 220      *
 221      * @param <X> Type of the exception to be thrown
 222      * @param exceptionSupplier The supplier which will return the exception to
 223      * be thrown
 224      * @return the present value
 225      * @throws X if there is no value present
 226      * @throws NullPointerException if no value is present and
 227      * {@code exceptionSupplier} is null
 228      */
 229     public<X extends Throwable> double orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
 230         if (isPresent) {
 231             return value;
 232         } else {
 233             throw exceptionSupplier.get();
 234         }
 235     }
 236 
 237     /**
 238      * Indicates whether some other object is "equal to" this OptionalDouble. The
 239      * other object is considered equal if:
 240      * <ul>
 241      * <li>it is also an {@code OptionalDouble} and;
 242      * <li>both instances have no value present or;
 243      * <li>the present values are "equal to" each other via {@code Double.compare() == 0}.
 244      * </ul>
 245      *
 246      * @param obj an object to be tested for equality
 247      * @return {code true} if the other object is "equal to" this object
 248      * otherwise {@code false}
 249      */
 250     @Override
 251     public boolean equals(Object obj) {
 252         if (this == obj) {
 253             return true;
 254         }
 255 
 256         if (!(obj instanceof OptionalDouble)) {
 257             return false;
 258         }
 259 
 260         OptionalDouble other = (OptionalDouble) obj;
 261         return (isPresent && other.isPresent)
 262                ? Double.compare(value, other.value) == 0
 263                : isPresent == other.isPresent;
 264     }
 265 
 266     /**
 267      * Returns the hash code value of the present value, if any, or 0 (zero) if
 268      * no value is present.
 269      *
 270      * @return hash code value of the present value or 0 if no value is present
 271      */
 272     @Override
 273     public int hashCode() {
 274         return isPresent ? Double.hashCode(value) : 0;
 275     }
 276 
 277     /**
 278      * {@inheritDoc}
 279      *
 280      * Returns a non-empty string representation of this object suitable for
 281      * debugging. The exact presentation format is unspecified and may vary
 282      * between implementations and versions.
 283      *
 284      * @implSpec If a value is present the result must include its string
 285      * representation in the result. Empty and present instances must be
 286      * unambiguously differentiable.
 287      *
 288      * @return the string representation of this instance
 289      */
 290     @Override
 291     public String toString() {
 292         return isPresent
 293                 ? String.format("OptionalDouble[%s]", value)
 294                 : "OptionalDouble.empty";
 295     }
 296 }