Pair.java

  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. import java.io.Serializable;
  19. import java.util.Map;
  20. import java.util.Objects;

  21. import org.apache.commons.lang3.builder.CompareToBuilder;
  22. import org.apache.commons.lang3.function.FailableBiConsumer;
  23. import org.apache.commons.lang3.function.FailableBiFunction;

  24. /**
  25.  * A pair consisting of two elements.
  26.  *
  27.  * <p>This class is an abstract implementation defining the basic API.
  28.  * It refers to the elements as 'left' and 'right'. It also implements the
  29.  * {@code Map.Entry} interface where the key is 'left' and the value is 'right'.</p>
  30.  *
  31.  * <p>Subclass implementations may be mutable or immutable.
  32.  * However, there is no restriction on the type of the stored objects that may be stored.
  33.  * If mutable objects are stored in the pair, then the pair itself effectively becomes mutable.</p>
  34.  *
  35.  * @param <L> the left element type.
  36.  * @param <R> the right element type.
  37.  * @since 3.0
  38.  */
  39. public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {

  40.     /** Serialization version */
  41.     private static final long serialVersionUID = 4954918890077093841L;

  42.     /**
  43.      * An empty array.
  44.      * <p>
  45.      * Consider using {@link #emptyArray()} to avoid generics warnings.
  46.      * </p>
  47.      *
  48.      * @since 3.10
  49.      */
  50.     public static final Pair<?, ?>[] EMPTY_ARRAY = {};

  51.     /**
  52.      * Returns the empty array singleton that can be assigned without compiler warning.
  53.      *
  54.      * @param <L> the left element type.
  55.      * @param <R> the right element type.
  56.      * @return the empty array singleton that can be assigned without compiler warning.
  57.      * @since 3.10
  58.      */
  59.     @SuppressWarnings("unchecked")
  60.     public static <L, R> Pair<L, R>[] emptyArray() {
  61.         return (Pair<L, R>[]) EMPTY_ARRAY;
  62.     }

  63.     /**
  64.      * Creates an immutable pair of two objects inferring the generic types.
  65.      *
  66.      * <p>This factory allows the pair to be created using inference to
  67.      * obtain the generic types.</p>
  68.      *
  69.      * @param <L> the left element type.
  70.      * @param <R> the right element type.
  71.      * @param left  the left element, may be null.
  72.      * @param right  the right element, may be null.
  73.      * @return a pair formed from the two parameters, not null.
  74.      */
  75.     public static <L, R> Pair<L, R> of(final L left, final R right) {
  76.         return ImmutablePair.of(left, right);
  77.     }

  78.     /**
  79.      * Creates an immutable pair from a map entry.
  80.      *
  81.      * <p>This factory allows the pair to be created using inference to
  82.      * obtain the generic types.</p>
  83.      *
  84.      * @param <L> the left element type.
  85.      * @param <R> the right element type.
  86.      * @param pair the map entry.
  87.      * @return a pair formed from the map entry.
  88.      * @since 3.10
  89.      */
  90.     public static <L, R> Pair<L, R> of(final Map.Entry<L, R> pair) {
  91.         return ImmutablePair.of(pair);
  92.     }

  93.     /**
  94.      * Creates an immutable pair of two non-null objects inferring the generic types.
  95.      *
  96.      * <p>This factory allows the pair to be created using inference to
  97.      * obtain the generic types.</p>
  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 a 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.      * Constructs a new instance.
  112.      */
  113.     public Pair() {
  114.         // empty
  115.     }

  116.     /**
  117.      * Accepts this key and value as arguments to the given consumer.
  118.      *
  119.      * @param <E> The kind of thrown exception or error.
  120.      * @param consumer the consumer to call.
  121.      * @throws E Thrown when the consumer fails.
  122.      * @since 3.13.0
  123.      */
  124.     public <E extends Throwable> void accept(final FailableBiConsumer<L, R, E> consumer) throws E {
  125.         consumer.accept(getKey(), getValue());
  126.     }

  127.     /**
  128.      * Applies this key and value as arguments to the given function.
  129.      *
  130.      * @param <V> The function return type.
  131.      * @param <E> The kind of thrown exception or error.
  132.      * @param function the consumer to call.
  133.      * @return the function's return value.
  134.      * @throws E Thrown when the consumer fails.
  135.      * @since 3.13.0
  136.      */
  137.     public <V, E extends Throwable> V apply(final FailableBiFunction<L, R, V, E> function) throws E {
  138.         return function.apply(getKey(), getValue());
  139.     }

  140.     /**
  141.      * Compares the pair based on the left element followed by the right element.
  142.      * The types must be {@link Comparable}.
  143.      *
  144.      * @param other  the other pair, not null.
  145.      * @return negative if this is less, zero if equal, positive if greater.
  146.      */
  147.     @Override
  148.     public int compareTo(final Pair<L, R> other) {
  149.         // @formatter:off
  150.         return new CompareToBuilder()
  151.             .append(getLeft(), other.getLeft())
  152.             .append(getRight(), other.getRight())
  153.             .toComparison();
  154.         // @formatter:on
  155.     }

  156.     /**
  157.      * Compares this pair to another based on the two elements.
  158.      *
  159.      * @param obj  the object to compare to, null returns false.
  160.      * @return true if the elements of the pair are equal.
  161.      */
  162.     @Override
  163.     public boolean equals(final Object obj) {
  164.         if (obj == this) {
  165.             return true;
  166.         }
  167.         if (obj instanceof Map.Entry<?, ?>) {
  168.             final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
  169.             return Objects.equals(getKey(), other.getKey())
  170.                     && Objects.equals(getValue(), other.getValue());
  171.         }
  172.         return false;
  173.     }

  174.     /**
  175.      * Gets the key from this pair.
  176.      *
  177.      * <p>This method implements the {@code Map.Entry} interface returning the
  178.      * left element as the key.</p>
  179.      *
  180.      * @return the left element as the key, may be null.
  181.      */
  182.     @Override
  183.     public final L getKey() {
  184.         return getLeft();
  185.     }

  186.     /**
  187.      * Gets the left element from this pair.
  188.      *
  189.      * <p>When treated as a key-value pair, this is the key.</p>
  190.      *
  191.      * @return the left element, may be null.
  192.      */
  193.     public abstract L getLeft();

  194.     /**
  195.      * Gets the right element from this pair.
  196.      *
  197.      * <p>When treated as a key-value pair, this is the value.</p>
  198.      *
  199.      * @return the right element, may be null.
  200.      */
  201.     public abstract R getRight();

  202.     /**
  203.      * Gets the value from this pair.
  204.      *
  205.      * <p>This method implements the {@code Map.Entry} interface returning the
  206.      * right element as the value.</p>
  207.      *
  208.      * @return the right element as the value, may be null.
  209.      */
  210.     @Override
  211.     public R getValue() {
  212.         return getRight();
  213.     }

  214.     /**
  215.      * Returns a suitable hash code.
  216.      * <p>
  217.      * The hash code follows the definition in {@code Map.Entry}.
  218.      * </p>
  219.      *
  220.      * @return the hash code.
  221.      */
  222.     @Override
  223.     public int hashCode() {
  224.         // See Map.Entry API specification
  225.         return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
  226.     }

  227.     /**
  228.      * Returns a String representation of this pair using the format {@code (left,right)}.
  229.      *
  230.      * @return a string describing this object, not null.
  231.      */
  232.     @Override
  233.     public String toString() {
  234.         return "(" + getLeft() + ',' + getRight() + ')';
  235.     }

  236.     /**
  237.      * Formats the receiver using the given format.
  238.      *
  239.      * <p>
  240.      * 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
  241.      * the left element (key) and {@code %2$s} for the right element (value).
  242.      * </p>
  243.      *
  244.      * @param format the format string, optionally containing {@code %1$s} and {@code %2$s}, not null.
  245.      * @return the formatted string, not null.
  246.      * @see String#format(String, Object...)
  247.      */
  248.     public String toString(final String format) {
  249.         return String.format(format, getLeft(), getRight());
  250.     }

  251. }