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