47

Is there available a proven Java Pair class implementation?

I mean readily available, widely accepted and tested, maybe part of a more extensive library such as Apache Commons or Guava.

aioobe
  • 413,195
  • 112
  • 811
  • 826
yannisf
  • 6,016
  • 9
  • 39
  • 61
  • 6
    possible duplicate of [What is the equivalent of the C++ Pair in Java?](http://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java) – Thilo Sep 06 '11 at 07:52

6 Answers6

37

Yes, have a look at Apache Commons Pair.

Use sparingly, if at all; left and right doesn't really convey anything about the content or relation between the elements.

(The Pair class was deliberately left out of the standard Java API.)

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • +1. finally... Commons Lang 2 did not have that (without generics it is less interesting anyway) – Thilo Sep 06 '11 at 07:55
  • 1
    Seems that they split it into MutablePair and ImmutablePair since the beta (to which you linked), though: http://commons.apache.org/lang/api/org/apache/commons/lang3/tuple/Pair.html – Thilo Sep 06 '11 at 07:56
  • 2
    "`left` and `right` doesn't really convey anything about the content" Pair implements Map.Entry, so that you can at least also call them `key` and `value`. – Thilo Sep 06 '11 at 08:00
  • 2
    Hehe, good point. However, unless you really use it as a map entry (in which case I don't understand why you wouldn't use a Map.Entry) `key`/`value` probably don't describe the content very well anyway. – aioobe Sep 06 '11 at 08:03
  • 2
    Why it was left out deliberately: http://mail.openjdk.java.net/pipermail/core-libs-dev/2010-March/003995.html – Andrea Bergonzo Aug 24 '17 at 16:04
  • 1
    @AndreaBergonzo's comment should be linked whenever someone asks for pairs or tuples anywhere. – Dragas Feb 17 '19 at 07:26
14

Map.Entry

What about java.util.Map.Entry interface?

Two concrete implementation bundled with Java 6 and later:

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Simon G.
  • 6,587
  • 25
  • 30
9

Here is an implementation from the Android SDK:

/**
 * Container to ease passing around a tuple of two objects. This object provides a sensible
 * implementation of equals(), returning true if equals() is true on each of the contained
 * objects.
 */
public class Pair<F, S> {
    public final F first;
    public final S second;

    /**
     * Constructor for a Pair.
     *
     * @param first the first object in the Pair
     * @param second the second object in the pair
     */
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    /**
     * Checks the two objects for equality by delegating to their respective
     * {@link Object#equals(Object)} methods.
     *
     * @param o the {@link Pair} to which this one is to be checked for equality
     * @return true if the underlying objects of the Pair are both considered
     *         equal
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
    }

    /**
     * Compute a hash code using the hash codes of the underlying objects
     *
     * @return a hashcode of the Pair
     */
    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
    }

    /**
     * Convenience method for creating an appropriately typed pair.
     * @param a the first object in the Pair
     * @param b the second object in the pair
     * @return a Pair that is templatized with the types of a and b
     */
    public static <A, B> Pair <A, B> create(A a, B b) {
        return new Pair<A, B>(a, b);
    }
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
pommedeterresautee
  • 1,843
  • 1
  • 20
  • 24
8

I used AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry when need to store pairs (like size and object collection).

This piece from my production code:

public Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>>
        getEventTable(RiskClassifier classifier) {
    Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>> l1s = new HashMap<>();
    Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>> l2s = new HashMap<>();
    Map<L3Risk, List<Event>> l3s = new HashMap<>();
    List<Event> events = new ArrayList<>();
    ...
    map.put(l3s, events);
    map.put(l2s, new AbstractMap.SimpleImmutableEntry<>(l3Size, l3s));
    map.put(l1s, new AbstractMap.SimpleImmutableEntry<>(l2Size, l2s));
}

Code looks complicated but instead of Map.Entry you limited to array of object (with size 2) and lose type checks...

gavenkoa
  • 45,285
  • 19
  • 251
  • 303
6

JavaFX has it as javafx.util.Pair.

http://docs.oracle.com/javafx/2/api/javafx/util/Pair.html

If you include jfxrt.jar in Java SDK you can use it.

lamusique
  • 392
  • 4
  • 6
4

My solution was:

public class Pair<F, S> extends java.util.AbstractMap.SimpleImmutableEntry<F, S> {

    public  Pair( F f, S s ) {
        super( f, s );
    }

    public F getFirst() {
        return getKey();
    }

    public S getSecond() {
        return getValue();
    }

    public String toString() {
        return "["+getKey()+","+getValue()+"]";
    }

}

Very simple, with all the benefits of the wrapped AbstractMap.SimpleImmutableEntry class.

Pkunk
  • 71
  • 3