OptionalLong.java revision b0576a2458c789126957917d8d9cf2a58ec6762a
1/*
2 * Copyright (c) 2012, 2013, 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 */
25package java.util;
26
27import java.util.function.LongConsumer;
28import java.util.function.LongSupplier;
29import java.util.function.Supplier;
30
31/**
32 * A container object which may or may not contain a {@code long} value.
33 * If a value is present, {@code isPresent()} will return {@code true} and
34 * {@code getAsLong()} will return the value.
35 *
36 * <p>Additional methods that depend on the presence or absence of a contained
37 * value are provided, such as {@link #orElse(long) orElse()}
38 * (return a default value if value not present) and
39 * {@link #ifPresent(java.util.function.LongConsumer) ifPresent()} (execute a block
40 * of code if the value is present).
41 *
42 * @since 1.8
43 */
44public final class OptionalLong {
45    /**
46     * Common instance for {@code empty()}.
47     */
48    private static final OptionalLong EMPTY = new OptionalLong();
49
50    /**
51     * If true then the value is present, otherwise indicates no value is present
52     */
53    private final boolean isPresent;
54    private final long value;
55
56    /**
57     * Construct an empty instance.
58     *
59     * @implNote generally only one empty instance, {@link OptionalLong#EMPTY},
60     * should exist per VM.
61     */
62    private OptionalLong() {
63        this.isPresent = false;
64        this.value = 0;
65    }
66
67    /**
68     * Returns an empty {@code OptionalLong} instance.  No value is present for this
69     * OptionalLong.
70     *
71     * @apiNote Though it may be tempting to do so, avoid testing if an object
72     * is empty by comparing with {@code ==} against instances returned by
73     * {@code Option.empty()}. There is no guarantee that it is a singleton.
74     * Instead, use {@link #isPresent()}.
75     *
76     *  @return an empty {@code OptionalLong}.
77     */
78    public static OptionalLong empty() {
79        return EMPTY;
80    }
81
82    /**
83     * Construct an instance with the value present.
84     *
85     * @param value the long value to be present
86     */
87    private OptionalLong(long value) {
88        this.isPresent = true;
89        this.value = value;
90    }
91
92    /**
93     * Return an {@code OptionalLong} with the specified value present.
94     *
95     * @param value the value to be present
96     * @return an {@code OptionalLong} with the value present
97     */
98    public static OptionalLong of(long value) {
99        return new OptionalLong(value);
100    }
101
102    /**
103     * If a value is present in this {@code OptionalLong}, returns the value,
104     * otherwise throws {@code NoSuchElementException}.
105     *
106     * @return the value held by this {@code OptionalLong}
107     * @throws NoSuchElementException if there is no value present
108     *
109     * @see OptionalLong#isPresent()
110     */
111    public long getAsLong() {
112        if (!isPresent) {
113            throw new NoSuchElementException("No value present");
114        }
115        return value;
116    }
117
118    /**
119     * Return {@code true} if there is a value present, otherwise {@code false}.
120     *
121     * @return {@code true} if there is a value present, otherwise {@code false}
122     */
123    public boolean isPresent() {
124        return isPresent;
125    }
126
127    /**
128     * Have the specified consumer accept the value if a value is present,
129     * otherwise do nothing.
130     *
131     * @param consumer block to be executed if a value is present
132     * @throws NullPointerException if value is present and {@code consumer} is
133     * null
134     */
135    public void ifPresent(LongConsumer consumer) {
136        if (isPresent)
137            consumer.accept(value);
138    }
139
140    /**
141     * Return the value if present, otherwise return {@code other}.
142     *
143     * @param other the value to be returned if there is no value present
144     * @return the value, if present, otherwise {@code other}
145     */
146    public long orElse(long other) {
147        return isPresent ? value : other;
148    }
149
150    /**
151     * Return the value if present, otherwise invoke {@code other} and return
152     * the result of that invocation.
153     *
154     * @param other a {@code LongSupplier} whose result is returned if no value
155     * is present
156     * @return the value if present otherwise the result of {@code other.getAsLong()}
157     * @throws NullPointerException if value is not present and {@code other} is
158     * null
159     */
160    public long orElseGet(LongSupplier other) {
161        return isPresent ? value : other.getAsLong();
162    }
163
164    /**
165     * Return the contained value, if present, otherwise throw an exception
166     * to be created by the provided supplier.
167     *
168     * @apiNote A method reference to the exception constructor with an empty
169     * argument list can be used as the supplier. For example,
170     * {@code IllegalStateException::new}
171     *
172     * @param <X> Type of the exception to be thrown
173     * @param exceptionSupplier The supplier which will return the exception to
174     * be thrown
175     * @return the present value
176     * @throws X if there is no value present
177     * @throws NullPointerException if no value is present and
178     * {@code exceptionSupplier} is null
179     */
180    public<X extends Throwable> long orElseThrow(Supplier<X> exceptionSupplier) throws X {
181        if (isPresent) {
182            return value;
183        } else {
184            throw exceptionSupplier.get();
185        }
186    }
187
188    /**
189     * Indicates whether some other object is "equal to" this OptionalLong. The
190     * other object is considered equal if:
191     * <ul>
192     * <li>it is also an {@code OptionalLong} and;
193     * <li>both instances have no value present or;
194     * <li>the present values are "equal to" each other via {@code ==}.
195     * </ul>
196     *
197     * @param obj an object to be tested for equality
198     * @return {code true} if the other object is "equal to" this object
199     * otherwise {@code false}
200     */
201    @Override
202    public boolean equals(Object obj) {
203        if (this == obj) {
204            return true;
205        }
206
207        if (!(obj instanceof OptionalLong)) {
208            return false;
209        }
210
211        OptionalLong other = (OptionalLong) obj;
212        return (isPresent && other.isPresent)
213                ? value == other.value
214                : isPresent == other.isPresent;
215    }
216
217    /**
218     * Returns the hash code value of the present value, if any, or 0 (zero) if
219     * no value is present.
220     *
221     * @return hash code value of the present value or 0 if no value is present
222     */
223    @Override
224    public int hashCode() {
225        return isPresent ? Long.hashCode(value) : 0;
226    }
227
228    /**
229     * {@inheritDoc}
230     *
231     * Returns a non-empty string representation of this object suitable for
232     * debugging. The exact presentation format is unspecified and may vary
233     * between implementations and versions.
234     *
235     * @implSpec If a value is present the result must include its string
236     * representation in the result. Empty and present instances must be
237     * unambiguously differentiable.
238     *
239     * @return the string representation of this instance
240     */
241    @Override
242    public String toString() {
243        return isPresent
244                ? String.format("OptionalLong[%s]", value)
245                : "OptionalLong.empty";
246    }
247}
248