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