    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>This class is an abstract implementation defining the basic API.
    031 * It refers to the elements as 'left' and 'right'. It also implements the
    032 * {@code Map.Entry} interface where the key is 'left' and the value is 'right'.</p>
    033 *
    034 * <p>Subclass implementations may be mutable or immutable.
    035 * However, there is no restriction on the type of the stored objects that may be stored.
    036 * If mutable objects are stored in the pair, then the pair itself effectively becomes mutable.</p>
    037 *
    038 * @param <L> the left element type.
    039 * @param <R> the right element type.
    040 * @since 3.0
    041 */
    042public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
    043
    044    /** Serialization version */
    045    private static final long serialVersionUID = 4954918890077093841L;
    046
    047    /**
    048     * An empty array.
    049     * <p>
    050     * Consider using {@link #emptyArray()} to avoid generics warnings.
    051     * </p>
    052     *
    053     * @since 3.10
    054     */
    055    public static final Pair<?, ?>[] EMPTY_ARRAY = {};
    056
    057    /**
    058     * Returns the empty array singleton that can be assigned without compiler warning.
    059     *
    060     * @param <L> the left element type.
    061     * @param <R> the right element type.
    062     * @return the empty array singleton that can be assigned without compiler warning.
    063     * @since 3.10
    064     */
    065    @SuppressWarnings("unchecked")
    066    public static <L, R> Pair<L, R>[] emptyArray() {
    067        return (Pair<L, R>[]) EMPTY_ARRAY;
    068    }
    069
    070    /**
    071     * Creates an immutable pair of two objects inferring the generic types.
    072     *
    073     * <p>This factory allows the pair to be created using inference to
    074     * obtain the generic types.</p>
    075     *
    076     * @param <L> the left element type.
    077     * @param <R> the right element type.
    078     * @param left  the left element, may be null.
    079     * @param right  the right element, may be null.
    080     * @return a pair formed from the two parameters, not null.
    081     */
    082    public static <L, R> Pair<L, R> of(final L left, final R right) {
    083        return ImmutablePair.of(left, right);
    084    }
    085
    086    /**
    087     * Creates an immutable pair from a map entry.
    088     *
    089     * <p>This factory allows the pair to be created using inference to
    090     * obtain the generic types.</p>
    091     *
    092     * @param <L> the left element type.
    093     * @param <R> the right element type.
    094     * @param pair the map entry.
    095     * @return a pair formed from the map entry.
    096     * @since 3.10
    097     */
    098    public static <L, R> Pair<L, R> of(final Map.Entry<L, R> pair) {
    099        return ImmutablePair.of(pair);
    100    }
    101
    102    /**
    103     * Creates an immutable pair of two non-null objects inferring the generic types.
    104     *
    105     * <p>This factory allows the pair to be created using inference to
    106     * obtain the generic types.</p>
    107     *
    108     * @param <L> the left element type.
    109     * @param <R> the right element type.
    110     * @param left  the left element, may not be null.
    111     * @param right  the right element, may not  be null.
    112     * @return a pair formed from the two parameters, not null.
    113     * @throws NullPointerException if any input is null.
    114     * @since 3.13.0
    115     */
    116    public static <L, R> Pair<L, R> ofNonNull(final L left, final R right) {
    117        return ImmutablePair.ofNonNull(left, right);
    118    }
    119
    120    /**
    121     * Constructs a new instance.
    122     */
    123    public Pair() {
    124        // empty
    125    }
    126
    127    /**
    128     * Accepts this key and value as arguments to the given consumer.
    129     *
    130     * @param <E> The kind of thrown exception or error.
    131     * @param consumer the consumer to call.
    132     * @throws E Thrown when the consumer fails.
    133     * @since 3.13.0
    134     */
    135    public <E extends Throwable> void accept(final FailableBiConsumer<L, R, E> consumer) throws E {
    136        consumer.accept(getKey(), getValue());
    137    }
    138
    139    /**
    140     * Applies this key and value as arguments to the given function.
    141     *
    142     * @param <V> The function return type.
    143     * @param <E> The kind of thrown exception or error.
    144     * @param function the consumer to call.
    145     * @return the function's return value.
    146     * @throws E Thrown when the consumer fails.
    147     * @since 3.13.0
    148     */
    149    public <V, E extends Throwable> V apply(final FailableBiFunction<L, R, V, E> function) throws E {
    150        return function.apply(getKey(), getValue());
    151    }
    152
    153    /**
    154     * Compares the pair based on the left element followed by the right element.
    155     * The types must be {@link Comparable}.
    156     *
    157     * @param other  the other pair, not null.
    158     * @return negative if this is less, zero if equal, positive if greater.
    159     */
    160    @Override
    161    public int compareTo(final Pair<L, R> other) {
    162        // @formatter:off
    163        return new CompareToBuilder()
    164            .append(getLeft(), other.getLeft())
    165            .append(getRight(), other.getRight())
    166            .toComparison();
    167        // @formatter:on
    168    }
    169
    170    /**
    171     * Compares this pair to another based on the two elements.
    172     *
    173     * @param obj  the object to compare to, null returns false.
    174     * @return true if the elements of the pair are equal.
    175     */
    176    @Override
    177    public boolean equals(final Object obj) {
    178        if (obj == this) {
    179            return true;
    180        }
    181        if (obj instanceof Map.Entry<?, ?>) {
    182            final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
    183            return Objects.equals(getKey(), other.getKey())
    184                    && Objects.equals(getValue(), other.getValue());
    185        }
    186        return false;
    187    }
    188
    189    /**
    190     * Gets the key from this pair.
    191     *
    192     * <p>This method implements the {@code Map.Entry} interface returning the
    193     * left element as the key.</p>
    194     *
    195     * @return the left element as the key, may be null.
    196     */
    197    @Override
    198    public final L getKey() {
    199        return getLeft();
    200    }
    201
    202    /**
    203     * Gets the left element from this pair.
    204     *
    205     * <p>When treated as a key-value pair, this is the key.</p>
    206     *
    207     * @return the left element, may be null.
    208     */
    209    public abstract L getLeft();
    210
    211    /**
    212     * Gets the right element from this pair.
    213     *
    214     * <p>When treated as a key-value pair, this is the value.</p>
    215     *
    216     * @return the right element, may be null.
    217     */
    218    public abstract R getRight();
    219
    220    /**
    221     * Gets the value from this pair.
    222     *
    223     * <p>This method implements the {@code Map.Entry} interface returning the
    224     * right element as the value.</p>
    225     *
    226     * @return the right element as the value, may be null.
    227     */
    228    @Override
    229    public R getValue() {
    230        return getRight();
    231    }
    232
    233    /**
    234     * Returns a suitable hash code.
    235     * <p>
    236     * The hash code follows the definition in {@code Map.Entry}.
    237     * </p>
    238     *
    239     * @return the hash code.
    240     */
    241    @Override
    242    public int hashCode() {
    243        // See Map.Entry API specification
    244        return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
    245    }
    246
    247    /**
    248     * Returns a String representation of this pair using the format {@code (left,right)}.
    249     *
    250     * @return a string describing this object, not null.
    251     */
    252    @Override
    253    public String toString() {
    254        return "(" + getLeft() + ',' + getRight() + ')';
    255    }
    256
    257    /**
    258     * Formats the receiver using the given format.
    259     *
    260     * <p>
    261     * 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
    262     * the left element (key) and {@code %2$s} for the right element (value).
    263     * </p>
    264     *
    265     * @param format the format string, optionally containing {@code %1$s} and {@code %2$s}, not null.
    266     * @return the formatted string, not null.
    267     * @see String#format(String, Object...)
    268     */
    269    public String toString(final String format) {
    270        return String.format(format, getLeft(), getRight());
    271    }
    272
    273}