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