Application scenario:
When it comes to key value pairs, we usually use Map mapping to process them. At this time, the key is equivalent to a description or reference of value, and the specific information is saved in value. We can get the corresponding value through key. But when both key and value store specific information, we need to use Pair pair.
In fact, what Pair stores is a Pair of information, both of which are what we need. There is no difference between key and value.
Specific implementation:
1. Under the javax.util package, there is a simple Pair class.
/** * Key of this <code>Pair</code>. */ private K key; /** * Gets the key for this pair. * @return key for this pair */ public K getKey() { return key; } /** * Value of this this <code>Pair</code>. */ private V value; /** * Gets the value for this pair. * @return value for this pair */ public V getValue() { return value; } /** * Creates a new pair * @param key The key for this pair * @param value The value to use for this pair */ public Pair(@NamedArg("key") K key, @NamedArg("value") V value) { this.key = key; this.value = value; }
Usage:
Pair<String, String> pair = new Pair<>("aku", "female"); pair.getKey(); pair.getValue();
2. In the Apache Commons library, the org.apache.commons.lang3.tuple package provides the Pair abstract class, which has two subclasses, namely immutable Pair and MutablePair. Both implement access to key/value and setter and getter methods.
public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable { /** * @return Returns an immutable Pair of pairs */ public static <L, R> Pair<L, R> of(final L left, final R right) { return new ImmutablePair<>(left, right); } public abstract L getLeft(); public abstract R getRight(); @Override public final L getKey() { return getLeft(); } @Override public R getValue() { return getRight(); } }
Usage:
Pair<String, String> pair = Pair.of("aku", "female"); pair.getLeft(); pair.getRight();