1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.lang3.tuple;
18
19 import java.io.Serializable;
20 import java.util.Map;
21 import java.util.Objects;
22
23 import org.apache.commons.lang3.builder.CompareToBuilder;
24 import org.apache.commons.lang3.function.FailableBiConsumer;
25 import org.apache.commons.lang3.function.FailableBiFunction;
26
27 /**
28 * A pair consisting of two elements.
29 *
30 * <p>This class is an abstract implementation defining the basic API.
31 * It refers to the elements as 'left' and 'right'. It also implements the
32 * {@code Map.Entry} interface where the key is 'left' and the value is 'right'.</p>
33 *
34 * <p>Subclass implementations may be mutable or immutable.
35 * However, there is no restriction on the type of the stored objects that may be stored.
36 * If mutable objects are stored in the pair, then the pair itself effectively becomes mutable.</p>
37 *
38 * @param <L> the left element type.
39 * @param <R> the right element type.
40 * @since 3.0
41 */
42 public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
43
44 /** Serialization version */
45 private static final long serialVersionUID = 4954918890077093841L;
46
47 /**
48 * An empty array.
49 * <p>
50 * Consider using {@link #emptyArray()} to avoid generics warnings.
51 * </p>
52 *
53 * @since 3.10
54 */
55 public static final Pair<?, ?>[] EMPTY_ARRAY = {};
56
57 /**
58 * Returns the empty array singleton that can be assigned without compiler warning.
59 *
60 * @param <L> the left element type.
61 * @param <R> the right element type.
62 * @return the empty array singleton that can be assigned without compiler warning.
63 * @since 3.10
64 */
65 @SuppressWarnings("unchecked")
66 public static <L, R> Pair<L, R>[] emptyArray() {
67 return (Pair<L, R>[]) EMPTY_ARRAY;
68 }
69
70 /**
71 * Creates an immutable pair of two objects inferring the generic types.
72 *
73 * @param <L> the left element type.
74 * @param <R> the right element type.
75 * @param left the left element, may be null.
76 * @param right the right element, may be null.
77 * @return an immutable pair formed from the two parameters, not null.
78 */
79 public static <L, R> Pair<L, R> of(final L left, final R right) {
80 return ImmutablePair.of(left, right);
81 }
82
83 /**
84 * Creates an immutable pair from a map entry.
85 *
86 * @param <L> the left element type.
87 * @param <R> the right element type.
88 * @param pair the map entry.
89 * @return an immutable pair formed from the map entry.
90 * @since 3.10
91 */
92 public static <L, R> Pair<L, R> of(final Map.Entry<L, R> pair) {
93 return ImmutablePair.of(pair);
94 }
95
96 /**
97 * Creates an immutable pair of two non-null objects inferring the generic types.
98 *
99 * @param <L> the left element type.
100 * @param <R> the right element type.
101 * @param left the left element, may not be null.
102 * @param right the right element, may not be null.
103 * @return an immutable pair formed from the two parameters, not null.
104 * @throws NullPointerException if any input is null.
105 * @since 3.13.0
106 */
107 public static <L, R> Pair<L, R> ofNonNull(final L left, final R right) {
108 return ImmutablePair.ofNonNull(left, right);
109 }
110
111 /**
112 * Constructs a new instance.
113 */
114 public Pair() {
115 // empty
116 }
117
118 /**
119 * Accepts this key and value as arguments to the given consumer.
120 *
121 * @param <E> The kind of thrown exception or error.
122 * @param consumer the consumer to call.
123 * @throws E Thrown when the consumer fails.
124 * @since 3.13.0
125 */
126 public <E extends Throwable> void accept(final FailableBiConsumer<L, R, E> consumer) throws E {
127 consumer.accept(getKey(), getValue());
128 }
129
130 /**
131 * Applies this key and value as arguments to the given function.
132 *
133 * @param <V> The function return type.
134 * @param <E> The kind of thrown exception or error.
135 * @param function the consumer to call.
136 * @return the function's return value.
137 * @throws E Thrown when the consumer fails.
138 * @since 3.13.0
139 */
140 public <V, E extends Throwable> V apply(final FailableBiFunction<L, R, V, E> function) throws E {
141 return function.apply(getKey(), getValue());
142 }
143
144 /**
145 * Compares the pair based on the left element followed by the right element.
146 * The types must be {@link Comparable}.
147 *
148 * @param other the other pair, not null.
149 * @return negative if this is less, zero if equal, positive if greater.
150 */
151 @Override
152 public int compareTo(final Pair<L, R> other) {
153 // @formatter:off
154 return new CompareToBuilder()
155 .append(getLeft(), other.getLeft())
156 .append(getRight(), other.getRight())
157 .toComparison();
158 // @formatter:on
159 }
160
161 /**
162 * Compares this pair to another based on the two elements.
163 *
164 * @param obj the object to compare to, null returns false.
165 * @return true if the elements of the pair are equal.
166 */
167 @Override
168 public boolean equals(final Object obj) {
169 if (obj == this) {
170 return true;
171 }
172 if (obj instanceof Map.Entry<?, ?>) {
173 final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
174 return Objects.equals(getKey(), other.getKey())
175 && Objects.equals(getValue(), other.getValue());
176 }
177 return false;
178 }
179
180 /**
181 * Gets the key from this pair.
182 *
183 * <p>This method implements the {@code Map.Entry} interface returning the
184 * left element as the key.</p>
185 *
186 * @return the left element as the key, may be null.
187 */
188 @Override
189 public final L getKey() {
190 return getLeft();
191 }
192
193 /**
194 * Gets the left element from this pair.
195 *
196 * <p>When treated as a key-value pair, this is the key.</p>
197 *
198 * @return the left element, may be null.
199 */
200 public abstract L getLeft();
201
202 /**
203 * Gets the right element from this pair.
204 *
205 * <p>When treated as a key-value pair, this is the value.</p>
206 *
207 * @return the right element, may be null.
208 */
209 public abstract R getRight();
210
211 /**
212 * Gets the value from this pair.
213 *
214 * <p>This method implements the {@code Map.Entry} interface returning the
215 * right element as the value.</p>
216 *
217 * @return the right element as the value, may be null.
218 */
219 @Override
220 public R getValue() {
221 return getRight();
222 }
223
224 /**
225 * Returns a suitable hash code.
226 * <p>
227 * The hash code follows the definition in {@code Map.Entry}.
228 * </p>
229 *
230 * @return the hash code.
231 */
232 @Override
233 public int hashCode() {
234 // See Map.Entry API specification
235 return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
236 }
237
238 /**
239 * Returns a String representation of this pair using the format {@code (left,right)}.
240 *
241 * @return a string describing this object, not null.
242 */
243 @Override
244 public String toString() {
245 return "(" + getLeft() + ',' + getRight() + ')';
246 }
247
248 /**
249 * Formats the receiver using the given format.
250 *
251 * <p>
252 * 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
253 * the left element (key) and {@code %2$s} for the right element (value).
254 * </p>
255 *
256 * @param format the format string, optionally containing {@code %1$s} and {@code %2$s}, not null.
257 * @return the formatted string, not null.
258 * @see String#format(String, Object...)
259 */
260 public String toString(final String format) {
261 return String.format(format, getLeft(), getRight());
262 }
263
264 }