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.LongConsumer;
 28 import java.util.function.LongSupplier;
 29 import java.util.function.Supplier;
 30 import java.util.stream.LongStream;
 31 
 32 /**
 33  * A container object which may or may not contain a {@code long} 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(long) orElse()}
 40  * (returns a default value if no value is present) and
 41  * {@link #ifPresent(LongConsumer) ifPresent()} (performs an
 42  * 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 OptionalLong} 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 OptionalLong} should never itself be {@code null}; it should always point
 54  * to an {@code OptionalLong} instance.
 55  *
 56  * @since 1.8
 57  */
 58 @jdk.internal.ValueBased
 59 public final class OptionalLong {
 60     /**
 61      * Common instance for {@code empty()}.
 62      */
 63     private static final OptionalLong EMPTY = new OptionalLong();
 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 long value;
 70 
 71     /**
 72      * Construct an empty instance.
 73      *
 74      * @implNote generally only one empty instance, {@link OptionalLong#EMPTY},
 75      * should exist per VM.
 76      */
 77     private OptionalLong() {
 78         this.isPresent = false;
 79         this.value = 0;
 80     }
 81 
 82     /**
 83      * Returns an empty {@code OptionalLong} instance.  No value is present for
 84      * this {@code OptionalLong}.
 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 OptionalLong.empty()}.  There is no guarantee that it is a singleton.
 90      * Instead, use {@link #isEmpty()} or {@link #isPresent()}.
 91      *
 92      * @return an empty {@code OptionalLong}.
 93      */
 94     public static OptionalLong empty() {
 95         return EMPTY;
 96     }
 97 
 98     /**
 99      * Construct an instance with the described value.
100      *
101      * @param value the long value to describe
102      */
103     private OptionalLong(long value) {
104         this.isPresent = true;
105         this.value = value;
106     }
107 
108     /**
109      * Returns an {@code OptionalLong} describing the given value.
110      *
111      * @param value the value to describe
112      * @return an {@code OptionalLong} with the value present
113      */
114     public static OptionalLong of(long value) {
115         return new OptionalLong(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 OptionalLong}
126      * @throws NoSuchElementException if no value is present
127      */
128     public long getAsLong() {
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(LongConsumer 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(LongConsumer 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 LongStream} containing
191      * only that value, otherwise returns an empty {@code LongStream}.
192      *
193      * @apiNote
194      * This method can be used to transform a {@code Stream} of optional longs
195      * to an {@code LongStream} of present longs:
196      * <pre>{@code
197      *     Stream<OptionalLong> os = ..
198      *     LongStream s = os.flatMapToLong(OptionalLong::stream)
199      * }</pre>
200      *
201      * @return the optional value as an {@code LongStream}
202      * @since 9
203      */
204     public LongStream stream() {
205         if (isPresent) {
206             return LongStream.of(value);
207         } else {
208             return LongStream.empty();
209         }
210     }
211 
212     /**
213      * If a value is present, returns the value, otherwise returns
214      * {@code other}.
215      *
216      * @param other the value to be returned, if no value is present
217      * @return the value, if present, otherwise {@code other}
218      */
219     public long orElse(long other) {
220         return isPresent ? value : other;
221     }
222 
223     /**
224      * If a value is present, returns the value, otherwise returns the result
225      * produced by the supplying function.
226      *
227      * @param supplier the supplying function that produces a value to be returned
228      * @return the value, if present, otherwise the result produced by the
229      *         supplying function
230      * @throws NullPointerException if no value is present and the supplying
231      *         function is {@code null}
232      */
233     public long orElseGet(LongSupplier supplier) {
234         return isPresent ? value : supplier.getAsLong();
235     }
236 
237     /**
238      * If a value is present, returns the value, otherwise throws
239      * {@code NoSuchElementException}.
240      *
241      * @return the value described by this {@code OptionalLong}
242      * @throws NoSuchElementException if no value is present
243      * @since 10
244      */
245     public long orElseThrow() {
246         if (!isPresent) {
247             throw new NoSuchElementException("No value present");
248         }
249         return value;
250     }
251 
252     /**
253      * If a value is present, returns the value, otherwise throws an exception
254      * produced by the exception supplying function.
255      *
256      * @apiNote
257      * A method reference to the exception constructor with an empty argument
258      * list can be used as the supplier. For example,
259      * {@code IllegalStateException::new}
260      *
261      * @param <X> Type of the exception to be thrown
262      * @param exceptionSupplier the supplying function that produces an
263      *        exception to be thrown
264      * @return the value, if present
265      * @throws X if no value is present
266      * @throws NullPointerException if no value is present and the exception
267      *         supplying function is {@code null}
268      */
269     public<X extends Throwable> long orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
270         if (isPresent) {
271             return value;
272         } else {
273             throw exceptionSupplier.get();
274         }
275     }
276 
277     /**
278      * Indicates whether some other object is "equal to" this
279      * {@code OptionalLong}.  The other object is considered equal if:
280      * <ul>
281      * <li>it is also an {@code OptionalLong} and;
282      * <li>both instances have no value present or;
283      * <li>the present values are "equal to" each other via {@code ==}.
284      * </ul>
285      *
286      * @param obj an object to be tested for equality
287      * @return {@code true} if the other object is "equal to" this object
288      *         otherwise {@code false}
289      */
290     @Override
291     public boolean equals(Object obj) {
292         if (this == obj) {
293             return true;
294         }
295 
296         return obj instanceof OptionalLong other
297                 && (isPresent && other.isPresent
298                 ? value == other.value
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
310     public int hashCode() {
311         return isPresent ? Long.hashCode(value) : 0;
312     }
313 
314     /**
315      * Returns a non-empty string representation of this {@code OptionalLong}
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 OptionalLong}s must be
322      * unambiguously differentiable.
323      *
324      * @return the string representation of this instance
325      */
326     @Override
327     public String toString() {
328         return isPresent
329                 ? ("OptionalLong[" + value + "]")
330                 : "OptionalLong.empty";
331     }
332 }