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