001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3.tuple;
018
019import java.io.Serializable;
020import java.util.Map;
021import java.util.Objects;
022
023import org.apache.commons.lang3.builder.CompareToBuilder;
024import org.apache.commons.lang3.function.FailableBiConsumer;
025import org.apache.commons.lang3.function.FailableBiFunction;
026
027/**
028 * A pair consisting of two elements.
029 *
030 * <p>
031 * This class is an abstract implementation defining the basic API.
032 * It refers to the elements as 'left' and 'right'. It also implements the
033 * {@code Map.Entry} interface where the key is 'left' and the value is 'right'.
034 * </p>
035 *
036 * <p>
037 * Subclass implementations may be mutable or immutable.
038 * However, there is no restriction on the type of the stored objects that may be stored.
039 * If mutable objects are stored in the pair, then the pair itself effectively becomes mutable.
040 * </p>
041 *
042 * @param <L> The left element type.
043 * @param <R> The right element type.
044 * @since 3.0
045 */
046public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
047
048    /** Serialization version */
049    private static final long serialVersionUID = 4954918890077093841L;
050
051    /**
052     * An empty array.
053     * <p>
054     * Consider using {@link #emptyArray()} to avoid generics warnings.
055     * </p>
056     *
057     * @since 3.10
058     */
059    public static final Pair<?, ?>[] EMPTY_ARRAY = {};
060
061    /**
062     * Returns the empty array singleton that can be assigned without compiler warning.
063     *
064     * @param <L> The left element type.
065     * @param <R> The right element type.
066     * @return The empty array singleton that can be assigned without compiler warning.
067     * @since 3.10
068     */
069    @SuppressWarnings("unchecked")
070    public static <L, R> Pair<L, R>[] emptyArray() {
071        return (Pair<L, R>[]) EMPTY_ARRAY;
072    }
073
074    /**
075     * Creates an immutable pair of two objects inferring the generic types.
076     *
077     * @param <L> The left element type.
078     * @param <R> The right element type.
079     * @param left  The left element, may be null.
080     * @param right  The right element, may be null.
081     * @return An immutable pair formed from the two parameters, not null.
082     */
083    public static <L, R> Pair<L, R> of(final L left, final R right) {
084        return ImmutablePair.of(left, right);
085    }
086
087    /**
088     * Creates an immutable pair from a map entry.
089     *
090     * @param <L> The left element type.
091     * @param <R> The right element type.
092     * @param pair The map entry.
093     * @return An immutable pair formed from the map entry.
094     * @since 3.10
095     */
096    public static <L, R> Pair<L, R> of(final Map.Entry<L, R> pair) {
097        return ImmutablePair.of(pair);
098    }
099
100    /**
101     * Creates an immutable pair of two non-null objects inferring the generic types.
102     *
103     * @param <L> The left element type.
104     * @param <R> The right element type.
105     * @param left  The left element, may not be null.
106     * @param right  The right element, may not  be null.
107     * @return An immutable pair formed from the two parameters, not null.
108     * @throws NullPointerException Thrown if any input is null.
109     * @since 3.13.0
110     */
111    public static <L, R> Pair<L, R> ofNonNull(final L left, final R right) {
112        return ImmutablePair.ofNonNull(left, right);
113    }
114
115    /**
116     * Constructs a new instance.
117     */
118    public Pair() {
119        // empty
120    }
121
122    /**
123     * Accepts this key and value as arguments to the given consumer.
124     *
125     * @param <E> The kind of thrown exception or error.
126     * @param consumer The consumer to call.
127     * @throws E Thrown when the consumer fails.
128     * @since 3.13.0
129     */
130    public <E extends Throwable> void accept(final FailableBiConsumer<L, R, E> consumer) throws E {
131        consumer.accept(getKey(), getValue());
132    }
133
134    /**
135     * Applies this key and value as arguments to the given function.
136     *
137     * @param <V> The function return type.
138     * @param <E> The kind of thrown exception or error.
139     * @param function The consumer to call.
140     * @return The function's return value.
141     * @throws E Thrown when the consumer fails.
142     * @since 3.13.0
143     */
144    public <V, E extends Throwable> V apply(final FailableBiFunction<L, R, V, E> function) throws E {
145        return function.apply(getKey(), getValue());
146    }
147
148    /**
149     * Compares the pair based on the left element followed by the right element.
150     * The types must be {@link Comparable}.
151     *
152     * @param other  The other pair, not null.
153     * @return negative if this is less, zero if equal, positive if greater.
154     */
155    @Override
156    public int compareTo(final Pair<L, R> other) {
157        // @formatter:off
158        return new CompareToBuilder()
159            .append(getLeft(), other.getLeft())
160            .append(getRight(), other.getRight())
161            .toComparison();
162        // @formatter:on
163    }
164
165    /**
166     * Compares this pair to another based on the two elements.
167     *
168     * @param obj  The object to compare to, null returns false.
169     * @return true if the elements of the pair are equal.
170     */
171    @Override
172    public boolean equals(final Object obj) {
173        if (obj == this) {
174            return true;
175        }
176        if (obj instanceof Map.Entry<?, ?>) {
177            final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
178            return Objects.equals(getKey(), other.getKey())
179                    && Objects.equals(getValue(), other.getValue());
180        }
181        return false;
182    }
183
184    /**
185     * Gets the key from this pair.
186     *
187     * <p>
188     * This method implements the {@code Map.Entry} interface returning the
189     * left element as the key.
190     * </p>
191     *
192     * @return The left element as the key, may be null.
193     */
194    @Override
195    public final L getKey() {
196        return getLeft();
197    }
198
199    /**
200     * Gets the left element from this pair.
201     *
202     * <p>
203     * When treated as a key-value pair, this is the key.
204     * </p>
205     *
206     * @return The left element, may be null.
207     */
208    public abstract L getLeft();
209
210    /**
211     * Gets the right element from this pair.
212     *
213     * <p>
214     * When treated as a key-value pair, this is the value.
215     * </p>
216     *
217     * @return The right element, may be null.
218     */
219    public abstract R getRight();
220
221    /**
222     * Gets the value from this pair.
223     *
224     * <p>
225     * This method implements the {@code Map.Entry} interface returning the
226     * right element as the value.
227     * </p>
228     *
229     * @return The right element as the value, may be null.
230     */
231    @Override
232    public R getValue() {
233        return getRight();
234    }
235
236    /**
237     * Returns a suitable hash code.
238     * <p>
239     * The hash code follows the definition in {@code Map.Entry}.
240     * </p>
241     *
242     * @return The hash code.
243     */
244    @Override
245    public int hashCode() {
246        // See Map.Entry API specification
247        return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
248    }
249
250    /**
251     * Returns a String representation of this pair using the format {@code (left,right)}.
252     *
253     * @return A string describing this object, not null.
254     */
255    @Override
256    public String toString() {
257        return "(" + getLeft() + ',' + getRight() + ')';
258    }
259
260    /**
261     * Formats the receiver using the given format.
262     *
263     * <p>
264     * This uses {@link String#format(String, Object...)} to the format. Two variables may be used to embed the left and right elements. Use {@code %1$s} for
265     * the left element (key) and {@code %2$s} for the right element (value).
266     * </p>
267     *
268     * @param format The format string, optionally containing {@code %1$s} and {@code %2$s}, not null.
269     * @return The formatted string, not null.
270     * @see String#format(String, Object...)
271     */
272    public String toString(final String format) {
273        return String.format(format, getLeft(), getRight());
274    }
275
276}