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