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