![]() |
VOOZH | about |
A Pair is a Tuple from JavaTuples library that deals with 2 elements. Since this Pair is a generic class, it can hold any type of value in it.
Since Pair is a Tuple, hence it also has all the characteristics of JavaTuples:
public final class Pair<A, B> extends Tuple implements IValue0<A>, IValue1<B>
Object ↳ org.javatuples.Tuple ↳ org.javatuples.Pair<A, B>
Pair<A, B> pair = new Pair<A, B>(value1, value2);
Example:
Output:
[1, GeeksforGeeks]
Pair<type1, type2> pair = Pair.with(value1, value2);
Example:
Output:
[1, GeeksforGeeks]
Pair<type1, type2> pair = Pair.fromCollection(collectionWith_2_value); Pair<type1, type2> pair = Pair.fromArray(arrayWith_2_value);
Example:
Output:
[GeeksforGeeks, A computer portal] [GeeksforGeeks, A computer portal]
The getValueX() method can be used to fetch the value in a Tuple at index X. The indexing in Tuples start with 0. Hence the value at index X represents the value at position X+1.
Syntax:
Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); type1 val1 = pair.getValue0();
Example:
Output:
1
Since the Tuples are immutable, it means that modifying a value at an index is not possible. Hence, JavaTuples offer setAtX(value) which creates a copy of the Tuple with a new value at index X, and returns that Tuple.
Syntax:
Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); type1 val1 = pair.getValue0();
Example:
Output:
[1, A computer portal]
Adding a value can be done with the help of addAtX() method, where X represents the index at which the value is to be added. This method returns a Tuple of element one more than the called Tuple.
Syntax:
Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); Triplet<type 1, type 2, type 3> pair = pair.addAt2(value 2);
Example:
Output:
[1, GeeksforGeeks, A computer portal]
An element can be searched in a tuple with the pre-defined method contains(). It returns a boolean value whether the value is present or not.
Syntax:
Pair<type1, type2> pair = new Pair<type1, type2>(value1, value2); boolean res = pair.contains(value2);
Example:
Output:
true false
Since Pair implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays.
Syntax:
Pair<type1, type2> pair =
new Pair<type1, type2>(value1, value2);
for (Object item : pair) {
...
}
Example:
Output:
1 GeeksforGeeks