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.IntConsumer;
 28 import java.util.function.IntSupplier;
 29 import java.util.function.Supplier;
 30 import java.util.stream.IntStream;
 31 
 32 /**
 33  * A container object which may or may not contain an {@code int} 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(int) orElse()}
 40  * (returns a default value if no value is present) and
 41  * {@link #ifPresent(IntConsumer) 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 OptionalInt} 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 OptionalInt} should never itself be {@code null}; it should always point
 54  * to an {@code OptionalInt} instance.
 55  *
 56  * @since 1.8
 57  */
 58 @jdk.internal.ValueBased
 59 @jdk.internal.MigratedValueClass
 60 public final class OptionalInt {
 61     /**
 62      * Common instance for {@code empty()}.
 63      */
 64     private static final OptionalInt EMPTY = new OptionalInt();
 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 int value;
 71 
 72     /**
 73      * Construct an empty instance.
 74      *
 75      * @implNote Generally only one empty instance, {@link OptionalInt#EMPTY},
 76      * should exist per VM.
 77      */
 78     private OptionalInt() {
 79         this.isPresent = false;
 80         this.value = 0;
 81     }
 82 
 83     /**
 84      * Returns an empty {@code OptionalInt} instance.  No value is present for
 85      * this {@code OptionalInt}.
 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 OptionalInt.empty()}.  There is no guarantee that it is a singleton.
 91      * Instead, use {@link #isEmpty()} or {@link #isPresent()}.
 92      *
 93      * @return an empty {@code OptionalInt}
 94      */
 95     public static OptionalInt empty() {
 96         return EMPTY;
 97     }
 98 
 99     /**
100      * Construct an instance with the described value.
101      *
102      * @param value the int value to describe
103      */
104     private OptionalInt(int value) {
105         this.isPresent = true;
106         this.value = value;
107     }
108 
109     /**
110      * Returns an {@code OptionalInt} describing the given value.
111      *
112      * @param value the value to describe
113      * @return an {@code OptionalInt} with the value present
114      */
115     public static OptionalInt of(int value) {
116         return new OptionalInt(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 OptionalInt}
127      * @throws NoSuchElementException if no value is present
128      */
129     public int getAsInt() {
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(IntConsumer 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(IntConsumer 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 IntStream} containing
192      * only that value, otherwise returns an empty {@code IntStream}.
193      *
194      * @apiNote
195      * This method can be used to transform a {@code Stream} of optional
196      * integers to an {@code IntStream} of present integers:
197      * <pre>{@code
198      *     Stream<OptionalInt> os = ..
199      *     IntStream s = os.flatMapToInt(OptionalInt::stream)
200      * }</pre>
201      *
202      * @return the optional value as an {@code IntStream}
203      * @since 9
204      */
205     public IntStream stream() {
206         if (isPresent) {
207             return IntStream.of(value);
208         } else {
209             return IntStream.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 int orElse(int 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 int orElseGet(IntSupplier supplier) {
235         return isPresent ? value : supplier.getAsInt();
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 OptionalInt}
243      * @throws NoSuchElementException if no value is present
244      * @since 10
245      */
246     public int 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> int 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 OptionalInt}.  The other object is considered equal if:
281      * <ul>
282      * <li>it is also an {@code OptionalInt} and;
283      * <li>both instances have no value present or;
284      * <li>the present values are "equal to" each other via {@code ==}.
285      * </ul>
286      *
287      * @param obj an object to be tested for equality
288      * @return {@code true} if the other object is "equal to" this object
289      *         otherwise {@code false}
290      */
291     @Override
292     public boolean equals(Object obj) {
293         if (this == obj) {
294             return true;
295         }
296 
297         return obj instanceof OptionalInt other
298                 && (isPresent && other.isPresent
299                 ? value == other.value
300                 : isPresent == other.isPresent);
301     }
302 
303     /**
304      * Returns the hash code of the value, if present, otherwise {@code 0}
305      * (zero) if no value is present.
306      *
307      * @return hash code value of the present value or {@code 0} if no value is
308      *         present
309      */
310     @Override
311     public int hashCode() {
312         return isPresent ? Integer.hashCode(value) : 0;
313     }
314 
315     /**
316      * Returns a non-empty string representation of this {@code OptionalInt}
317      * suitable for debugging.  The exact presentation format is unspecified and
318      * may vary between implementations and versions.
319      *
320      * @implSpec
321      * If a value is present the result must include its string representation
322      * in the result.  Empty and present {@code OptionalInt}s must be
323      * unambiguously differentiable.
324      *
325      * @return the string representation of this instance
326      */
327     @Override
328     public String toString() {
329         return isPresent
330                 ? ("OptionalInt[" + value + "]")
331                 : "OptionalInt.empty";
332     }
333 }
--- EOF ---